Reputation:
There two "free(t)" on my function. When I call the function and goes to the first free(t) everything works fine, then the function self evokes itself and then, in the free(t) of the bottom of the code, occurs segmentation fail. Why this happens? And why the first "free(t)" doesnt result in segmentation fail and the secund result? Thanks
char c[50];
int b, j=0, d=0, e=0;
PLAYER *pt1;
MANAGER *pt2;
t=malloc(24*sizeof(TEAM));
tfile=fopen("team.txt", "r");
while(fscanf(tfile, "%d %s %d %d %d%c", &t[j].tablep, t[j].initials, &t[j].birth.day, &t[j].birth.month, &t[j].birth.year)!=EOF){
fgets(t[j].name, 50, tfile);
t[j].name[strlen(t[j].name)-1]='\0';
j++;
}
fclose(tfile);
t[j].name[0]=0;
j=0;
while(t[j].name[0]!=0){
printf("\t%i. %s\n", j+1, t[j].name);
j++;
}
do{
printf("What is the team of the player:");
scanf(" %c", &b);
b=b-48;
if(b<1 || b>j+1){
printf("Invalid choice. Try again.\n");
teamlists(a);
}
}while(b<1 || b>j);
j=0;
if(a==2){
}
else{ //(a==3)
pt2=malloc(sizeof(MANAGER));
memcpy(pt2, m, sizeof(*pt2));
m=malloc(24*sizeof(MANAGER));
reader(3);
while(m[j].name[0]!=0){
if(strcmp(m[j].team, t[b-1].name)==0){
do{
printf("This team already have a manager.\nEnter: \t1. to choose another team \t2. to return to menu ");
scanf(" %c", &e);
e=e-48;
if(e!=1 && e!=2)
printf("Invalid choice. Try again.\n");
if(e==1 || e==2){
free(t);
free(m);
}
if(e==1){
m=malloc(sizeof(MANAGER));
memcpy(m, pt2, sizeof(*m));
teamlists(a);
}
if(e==2){
main();
free(pt2);
}
}while(e!=1 && e!=2);
}
j++;
}
free(m);
memcpy(m, pt2, sizeof(*m));
strcpy(m->team, t[b-1].name);
free(t);
free(pt);
}
}
Upvotes: 0
Views: 59
Reputation: 1
7.22.3.3 The free function, paragraph 2 of the C standard states:
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
You're invoking undefined behavior by freeing the same pointer twice.
Your symptom is a fatal segmentation violation that kills your program.
Upvotes: 2