Consider the following program
typedef struct
{
char *name;
int id;
}Student;
int main()
{
Student std1,std2; //case 1
std1.name =(char*) malloc(7);
strcpy(std1.name, "Daniel");
puts(std1.name);
char name[7]={'D','a','n','i','e','l','\0'}; //case 2
std2.name = name;
puts(std2.name);
}
Case 1 place the name of the student in the heap memory while case 2 place the name of student2 in the sack memory, if I understand correctly.
My question is, why would I want to place the name (or any other field of structure) in the heap memory?
CodePudding user response:
If Case 2 works for you, by all means use it -- stack memory is faster to allocate, and is deallocated automatically.
You need Case 1 when the memory is too big to be on the stack (e.g. megabytes on typical systems), or it needs to outlive the function you allocate it in. It can typically happen when you allocate the struct
itself on the heap. E.g.:
Student *new_student() {
Student *p = malloc(sizeof(Student));
p->id = 0;
p->name = malloc(7);
strcpy(p->name, "Daniel");
return p;
}
In this example a stack allocation won't cut it.