Yes, you should. Every object pointed to by a pointer needs to be allocated somewhere. It can even be allocated in stack , but this is rare and would not work in this case. Then every object that will be pointed to by a variable, even if it is inside a structure, will be placed in the heap , you should have memory allocated with malloc()
or some substitute for it.
In this case both next
, and data
must have an allocation before.
Since they are pointers, are they pointing to where? How can you get a pointer? There are two basic forms (there are others of course):
- One is the use of the
&
operator that takes the address from something. The most common is to use with things that are in stack .
- The other is the use of an allocator such as
malloc()
that returns an address (a pointer.
Automatic allocation in C only when stack , and only for the element in stack , obviously not for possible notes inside it.
exp->data = malloc(sizeof( void*));
This does not work, or at least does not do what you think. It is a flexibility to have type void *
, but when allocating the space for an object pointed to by that pointer, you have to know the actual size of this object. This case is allocating space for a pointer, which will probably be 4 or 8 bytes depending on the architecture. Just this. You are not allocating space for the data that should be stored.
What is the size of the object that goes in data
? 50 bytes? Allocate 50 bytes. Is the size of 10 integers? 10 * sizeof(int)
. And so on.