char *t = malloc(2);
t = "as";
t = realloc(t,sizeof(char)*6);
I am getting error “invalid pointer: 0x080488d4 *“..
I am getting strange errors in using memory allocation functions. Is there any good tuts/guides which could explain me memory allocation functions.
I am using linux..
Please help..
This is your problem:
You probably thought this would copy the two-character string
"as"into the buffer you just allocated. What it actually does is throw away (leak) the buffer, and change the pointer to instead point to the string constant"as", which is stored in read-only memory next to the machine code, not on themallocheap. Because it’s not on the heap,realloclooks at the pointer and says “no can do, that’s not one of mine”. (The computer is being nice to you by giving you this error; when you giverealloca pointer that wasn’t returned bymallocorrealloc, the computer is allowed to make demons fly out of your nose if it wants.)This is how to do what you meant to do:
Note that you need space for three characters, not two, because of the implicit NUL terminator.
By the way, you never need to multiply anything by
sizeof(char); it is 1 by definition.