I wanted to create a generic Linked List in C. Following is the structure of the node:
typedef struct node {
void *value;
int size; // n bytes
ind index; // index of the node
struct node *next;
} Node;
And my delete_node function is as following. The search function sends a pointer to the Node I want to delete.
Node *search_list(Node *list, void *data, int n_bytes);
int delete_node(Node *list, Node *to_be_deleted); // returns 1 on success
Inside the delete_node function I want to free up the memory pointed by void *value and then free up the memory allocated for the Node itself.
free(to_be_deleted->value); // Would this work??
free(to_be_deleted);
Since it is void pointer we don’t know that how many bytes the object it is pointing to has occupied. How can we free up the memory for that?
Sorry if it is a stupid questions?
Straight forward answer ,
Yes this will work.simple thing :
see the definitions of
free()andmalloc()void free(void *) // free takes void* as argument so it will workvoid* malloc(sizeof(type))In
mallocwe have to pass thesizethat how many bytes we want to allocate.but in
freejust pass the pointer and whatever bytes allocated to that pointer on heap storage it will be freed