Reputation: 335
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?
Upvotes: 4
Views: 2251
Reputation: 59627
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.
Upvotes: 10
Reputation: 6064
p = a; // p points a
Executing this line, p should be pointing to const string (char *
).
You cannot free()
anything that is not obtained by calling malloc
or calloc
. Since in this example you try to free()
a const string, you get an error.
Upvotes: 0
Reputation: 7640
you actually meant memcpy(p,a,50); not p=a, remember C does not have a string data type.
Upvotes: 0
Reputation: 272657
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.
Upvotes: 12
Reputation: 41444
char a[50]
allocates an array of fifty characters on the stack. a
therefore points at an address on the stack.
p = a
sets p to point at the same address as a. Therefore after p = a
, p points at an address on the stack. Remember, p contains an address.
Afterwards, free(p)
tries to free a region of memory on the stack, which is illegal. You can only free memory you got from malloc().
Upvotes: 0