The example below presents a simple stack (FILO queue) implementation which uses the fixed-size memory management module to allocate and free memory blocks within a specified memory buffer.
#include <stdio.h>
#include "ST_API.h"
/* Data structure */
struct TStackData
{
/* Any type of data */
int Index;
};
/* Stack item */
struct TStackItem
{
PVOID Prev;
struct TStackData Data;
};
/* Stack buffer (512 bytes) */
UINT8 StackBuffer[512];
/* Stack pointer */
struct TStackItem *StackPointer;
/* Initialize stack */
BOOL InitStack(void)
{
/* Initialize memory buffer */
if(!stFixedMemInit(StackBuffer, sizeof(StackBuffer),
sizeof(struct TStackItem)))
return FALSE;
/* Initialize stack pointer */
StackPointer = NULL;
/* Return with success */
return TRUE;
}
/* Store message in the stack */
BOOL Push(struct TStackData FAR *Message)
{
struct TStackItem FAR *NewItem;
/* Allocate buffer for new data */
NewItem = (struct TStackItem FAR *) stFixedMemAlloc(StackBuffer);
/* Not enough memory in the buffer (stack is full) */
if(!NewItem)
return FALSE;
/* Copy item data */
stMemCpy(&NewItem->Data, Message, sizeof(*Message));
/* Update stack pointer. This section should be protected by a critical
section in a multitasking system */
NewItem->Prev = StackPointer;
StackPointer = NewItem;
/* Return with success */
return TRUE;
}
/* Read and remove message from the stack */
BOOL Pop(struct TStackData FAR *Message)
{
struct TStackItem FAR *Item;
/* Return failure if stack is empty */
if(!StackPointer)
return FALSE;
Item = StackPointer;
/* Update pointers. This section should be protected by a critical
section in a multitasking system */
StackPointer = StackPointer->Prev;
/* Copy item data */
stMemCpy(Message, &Item->Data, sizeof(*Message));
/* Release memory buffer */
stFixedMemFree(StackBuffer, Item);
/* Return with success */
return TRUE;
}
int test(void)
{
int i;
struct TStackData Message;
/* Initialization */
arInit();
stInit();
/* Initialize stack */
if(!InitStack())
{
printf("Failure during InitStack() function call.\n");
return 0;
}
/* Store 10 messages in the stack */
for(i = 0; i < 10; i++)
{
/* Prepare message (may be a local variable because it will be copied) */
Message.Index = i;
/* Store message */
if(Push(&Message))
printf("Message %i stored in the stack.\n", i);
/* Stop on failure (stack is full) */
else
{
printf("Failed to store new message.\n");
break;
}
}
/* Read all messages from the stack */
while(1)
{
/* Read next message */
if(Pop(&Message))
printf("Message %i has been read.\n", Message.Index);
/* Stop on failure (stack is empty) */
else
{
printf("All messages have been read.\n");
break;
}
}
/* Deinitialization */
arDeinit();
return 0;
}