efefefef efefefef - 2 months ago 7
C Question

Mallocing a pointer to another struct in C

I'm wondering if I have to allocate memory twice in this situation.
For instance:
consider that I have the structs:

struct ErrorCheck {
int returnValue;
struct Nodes * list;
};

struct Nodes {
char * name;
int grade;
struct Nodes * next;
};


And a function that mallocs them:

void buildList() {
struct ErrorCheck * newStruct;
newStruct = malloc(sizeof(struct ErrorCheck));
newStruct->list = malloc(sizeof(struct Nodes));

}


Do I have to malloc twice as shown above? Or is the first malloc sufficient, if I want to use both structs.

As in is:
newStruct = malloc(sizeof(struct ErrorCheck));
sufficient on it's own, is there a situation where either case can be true or false?

Answer

That actually depends what you want to do with list.

  • If you want list to act as a standalone variable with it's own memory where you can read from and write to, you'll be needing the second malloc().

  • If you want list to act like a placeholder, for example, assign some other already-allocated pointer to it and then use it, in that case, you don't need the ``malloc().

malloc()-ing for sizeof(struct ErrorCheck) and storing the pointer into newStruct gives you enough memory for the member variable themselves, i.e, it allocates memory for an int and an struct node * member variable. The memory address, where the pointer point to is indeterminate. You need to allocate memory seperately to the pointer variable to make it point to somewhere meaningful.

That said,

  • You should always check for the success of malloc() before using the returned pointer.
  • You need to call to free() for each allocation you do.
Comments