Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault when free() is used

Tags:

c++

c

string

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?

like image 761
learner Avatar asked Nov 29 '22 02:11

learner


2 Answers

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.

like image 20
pb2q Avatar answered Dec 06 '22 20:12

pb2q


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.


1. And it also causes a memory leak.
like image 179
Oliver Charlesworth Avatar answered Dec 06 '22 20:12

Oliver Charlesworth