Reputation: 13
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?
Upvotes: 1
Views: 149
Reputation: 11
There are a couple of things here.
You probably want to hold the pointer to the ErrorCheck structure in something other than a local variable which will disappear once the buildList function returns. You might return it from the function to the caller and store it somewhere more persistent (global variable or local variable in 'main'). You don't need to allocate the list variable right away but it would be a good idea to initialize it to NULL. Then use another function to add nodes by allocating the 'next' pointer and setting its contents (name, grade and NULL).
You can later step through the chain of nodes to list them or free them one by one when you are done. Freeing the list might be a little tricky for a new c coder; but that's another question.
Upvotes: 1
Reputation: 134286
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,
malloc()
before using the returned pointer.free()
for each allocation you do.Upvotes: 4
Reputation: 414
You need two malloc's. malloc only allocate memory for members of a structure. In your example, the first malloc allocates memory for two 8-byte pointers and an integer. A Node structure is not allocated automatically.
Upvotes: 0