#include <stdlib.h>
typedef struct stackObject
{
void* obj;
struct stackObject *next;
} StackObject_t;
typedef struct stackMeta
{
StackObject_t *stack;
size_t objsize;
int numelem;
} StackMeta_t;
//CREATE
StackMeta_t *mystack_create(size_t objsize)
{
StackMeta_t *elem;
elem = (StackMeta_t*)malloc(sizeof(StackMeta_t));
if(elem == NULL)
{
return NULL;
}
else
{
elem->stack = NULL; // my actual stack basically the first elem(the top)
elem->objsize = objsize; // size of the datatype
elem->numelem = 0; // total count of elem inside the stack
}
return elem;
}
//PUSH
int mystack_push(StackMeta_t *data_stack, void* obj)
{
if(data_stack == NULL)
{
return -1;
}
StackObject_t *nodeObject = NULL;
nodeObject = (StackObject_t*)malloc(sizeof(StackObject_t));
if(nodeObject == NULL)
{
return -1;
}
if(data_stack->stack == NULL)
{
nodeObject->next = NULL;
memcpy(nodeObject->obj, obj, data_stack->objsize);
data_stack->stack = nodeObject;
data_stack->numelem++;
}
else
{
nodeObject->next = data_stack->stack;
memcpy(nodeObject->obj, obj, data_stack->objsize);
data_stack->stack = nodeObject;
data_stack->numelem++;
}
return 0;
}
int main() {
StackMeta_t *METADATA = NULL;
int obj = 1;
METADATA = mystack_create(sizeof(int));
mystack_push(METADATA, &obj);
return 0;
}
This code is Stack with Linked List inside.
So I am trying to copy int obj
value to void* obj
. from my understanding obj
can be any data type so i chose it to be an int
type. I am using a visual online tool to see my heap memory and I saw that the value of the 3rd parameter is size_t objsize = 4
.
I cannot pin point where my problem is and I have not tested if this has memory leaks.
can someone explain this to me with an example on how to copy void pointers
?