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 free
on a block of memory that wasn't allocated using one of the malloc
methods.
When you do: p = a
you're assigning to p
the memory used by the stack array a
. That memory wasn't allocated using malloc
and hence it can't be freed using free
.
Furthermore with that re-assignment, you'll lose track of the block that you originally allocated with malloc
and assigned to p
, causing a memory leak.
This:
p = a;
copies the pointer, not the contents of the pointed-to memory. p
now points at the first element of the array a
. So when you do free(p)
, you're trying to free a non-dynamic array, which doesn't make any sense.1
You should investigate strncpy()
to copy strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With