I am new to C programming. I am working on a project for school which requires me to make use of malloc.
My question is this: is it better to call malloc before or after you assign something to the pointer
for example:
struct Node{
int value;
struct Node* next;
}
int main(int argc, char** argv){
struct Node* mylist = //something
//which of the following is the correct way to do this?
struct Node* node = mylist;
node = (struct Node*) malloc(1 * sizeof(struct Node));
//or
struct Node* node = (struct Node*) malloc(1 * sizeof(struct Node));
node = mylist;
}
mylist) and the second alternative also leaks the memory pointed to bynodeby overwriting thenodepointer.mylist = malloc(sizeof *mylist);, followed by assignment of its members, is sufficient.sizeof *mylist, notsizeof(mylist). As to what allocations are needed, you really should post more of howmylistis used.*node = *mylist;. But this is still a guess as you do not tell us what you actually are trying to achieve.