Yes, it should. Every object pointed by a pointer needs to be allocated somewhere. It can even be allocated to stack, but this is rare and would not work in this case. Then every object that will be pointed by a variable, even if it is within a structure, and will be placed in the heap, must have memory allocated with malloc()
or any substitute for him.
In this case both next
how much data
must have an allocation before.
As they are pointers are pointing to where? How can you get a pointer? There are two basic shapes (there are others, of course):
- One is the operator’s use
&
that picks up the address that something something. The most common is to use with things that are in the stack.
- The other is the use of an allocator like the
malloc()
that returns an address (a pointer.
Automatic allocation in C only when it is stack, and only for the element in stack, obviously not for possible notes inside it.
exp->data = malloc(sizeof(void*));
It doesn’t work, or at least it doesn’t do what you think it does. It’s a flexibility to have the type void *
, but when allocating space to object pointed 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, that’s it, not allocating space for the data that should be stored.
What is the size of the object that goes in data
? 50 bytes? Allot 50 bytes. Is the size of 10 integers? Allot 10 * sizeof(int)
. And so on and so forth.
Grateful for the response!
– Jaime38130