Ruchi
Ruchi

Reputation: 693

** glibc detected *** free(): invalid pointer: 0x0000000000400b2c

Consider the following code:

int main()
{
    char* s = (char*) malloc(sizeof(char)*10);
    s="hello";
    free(s);
}

When executing this program I get an error:

** glibc detected *** free(): invalid pointer: 0x0000000000400b2c

My research on this error indicates it may be caused by not assigning enough memory space via malloc(). But the program already calls malloc(), producing enough space for 10 chars.

Upvotes: 1

Views: 4261

Answers (5)

Hugh
Hugh

Reputation: 8932

You are reassigning s from the malloc'd pointer to a constant string literal, which you then try to free. As the string literal was not allocated with malloc, freeing it unsurprisingly leads to Bad Things.

Oh, and I see you've cast malloc's return. If you're using C, you should not do this; if you're using C++, then you should be using new/delete rather than malloc/free.

Upvotes: 2

EddieBytes
EddieBytes

Reputation: 1343

s="hello";

You are assigning another address to s, to a statically allocated memory. Freeing it is not correct. Also, since you are doing this, you are basically leaking the memory you have allocated here:

char* s = (char*) malloc(sizeof(char)*10);

Try:

int main()
{
    static const size_t kBufferSize = 10;
    char* s = (char*) malloc(sizeof(char) * kBufferSize);
    strncpy(s,"hello", kBufferSize); // better than strcpy, you are protecting
                            // yourself from a buffer overflow
    free(s);
}

Upvotes: 10

Mat
Mat

Reputation: 206909

After:

s="hello";

s no longer points to the memory you dynamically allocated. It points to that string literal "hello". You can't free that since it wasn't malloced in the first place. And you've leaked that allocation since you no longer have a pointer to it.

Look at the strncpy function to copy one C string to another.

Upvotes: 9

justin
justin

Reputation: 104718

the error is that you are freeing memory you do not own. you are freeing a string literal, rather than explicitly created memory requested via malloc/new & co..

Upvotes: 0

wallyk
wallyk

Reputation: 57804

It is an error to pass to free() anything not coming from malloc().

Assigning "hello" to s and then attempting to free it violates this rule.

Upvotes: 1

Related Questions