In a project, I was asked to create an INT128 type using int32_t and make postfixed calculations with them. I was using a generic stack to keep track of the operands. The code is below:
typedef struct int128
{
int32_t byteArray[4];
} INT128;
typedef struct node{
void *value;
struct node *bottom;
} NODE;
typedef struct stack{
int size;
size_t dataType;
NODE *top;
} STACK;
I used memcpy() to copy the value of an INT128 to the stack and back. It worked well when the stack had only char variables, but the results were completely different with the INT128 type. I'm not so familiar with memory manipulation, so theres probably something I'm not seeing here. Thanks!
Edit: Sorry guys...im using the functions below to push and pop data from the stack:
void push(STACK *machine,void *pushed)
{
NODE *newNode = malloc(sizeof(NODE));
newNode->value = malloc(machine->dataType);
memcpy(newNode->value,pushed,sizeof(machine->dataType));
newNode->bottom = machine->top;
machine->top = newNode;
machine->size++;
}
void pop(STACK *machine, void *poppedValue)
{
if(machine->top == NULL)
{
printf("WARNING: empty stack!\n");
}
else
{
NODE *popped = machine->top;
memcpy(poppedValue,popped->value,machine->dataType);
machine->top = popped->bottom;
free(popped->value);
free(popped);
machine->size--;
}
}
I'm initializing the stack like:
STACK *numStack = createStack(sizeof(INT128));
And using the push/pop functions normally.
There's a problem here:
newNode->value = malloc(machine->dataType);
memcpy(newNode->value,pushed,sizeof(machine->dataType));
You allocate machine->dataType
bytes, but then you copy sizeof machine->dataType
bytes. These may be different quantities, either causing a buffer overflow or causing bad behaviour due to not copying enough bytes.
I guess you probably meant to not use sizeof
in the second line.