** 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 char
s.
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);
}
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 malloc
ed 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.
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
, free
ing 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
.
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.
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..
精彩评论