This code causes a Segmentation Fault:
int main(){
char *p;
char a[50] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
p = (char *)malloc(50*sizeof(char));
if(!p){
cout << "Allocation Failure";
cout << "\n";
}
else{
cout << "Allocation Success";
cout << "\n";
p = a;
cout << p;
cout << "\n";
free(p);
}
return 0;
}
The output after executing this program is:
Allocation Success
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Segmentation fault
I am not able to find the bug. What may be reason?
You’re calling
freeon a block of memory that wasn’t allocated using one of themallocmethods.When you do:
p = ayou’re assigning topthe memory used by the stack arraya. That memory wasn’t allocated usingmallocand hence it can’t be freed usingfree.Furthermore with that re-assignment, you’ll lose track of the block that you originally allocated with
mallocand assigned top, causing a memory leak.