I have a simple struct s_person
and constructor(int number)
that takes the number of s_person
we want to construct and returns a pointer to it.
In this example I have constructed 2 s_person
, and assigned values to their attributes, name. And it works.
#include<stdio.h>
#include<stdlib.h>
#define MAX_NAME 50
typedef struct s_person {
char *name;
double grade;
}s_person;
s_person* construct(int number){
int each;
s_person *person = (s_person*)malloc(sizeof(s_person) * number);
if(person){
for(each=0; each<number; each++){
person[each].name = (char*)malloc(sizeof(char));
}
}
return person;
}
main()
{
s_person *person = construct(2);
person[0].name = "steven";
person[1].name = "michael";
printf("%s %s\n", person[0].name, person[1].name);
// This works
free(&person[0]);
printf("%s %s\n", person[0].name, person[1].name);
//This doesn't work
free(&person[1]); // Crashes here
printf("%s %s\n", person[0].name, person[1].name);
}
When I try to free the element 0 and print values again it works.
But if I try to free the element 1 and print values it crashes.
So, how can I free memory for the specific element in this array of structs?
And is it a valid way to make dynamically allocated memory for array of structs with constructor(int number)
function or is there a better practice?