So, I'm malloc()
ating a variable, something like this in a function in C:
char * foo;
foo = (char *)malloc(32 * sizeof(char) +1);
// some irrelevant (to the variable) code
function2(&foo);
free(foo);
And then, I copy a string into foo
in function2()
:
void function2(char ** foo)
{
// Some more (presumably) irrelevant code
strcpy(*foo, "asdf");
}
This is part of a much bigger project (a compiler). I wasn't able to reproduce this problem in a standalone C program, but stripping many of the variable dependencies, the above code seems ok.
My problem is, that the call to strcpy
causes a segfault 95% of the times (undefined behaviour the rest).
Following the execution with gdb
, I found that, up to this moment I can print foo
and see an empty string:
(gdb) s
1445 // line of code right before call to strcpy()
(gdb) print *foo
$18 = 0x6064c0 ""
(gdb) s
1455 strcpy(*foo, "asdf");
(gdb)
However, right before strcpy()
is called, print *foo
gets me a $19 = 0x2a00000002 <error: Cannot access memory at address 0x2a00000002>
and right after, most of the timesstrcpy()
will throw the SegFault, or the string will be corrupted and cause the next strcpy()
to throw the SegFault. Corruption is also random, as sometimes the pointer address will be intact (with gibberish characters), but sometimes 0x0
. The program may, occasionally, mess with other strings too, right at that point.
What causes that? Is *foo supposed to be freed before the call? Probably not. Could some other piece of code mess with its memory?
The strings seem to be properly allocated. I also tried with calloc(), allocating right before the strcpy()
call, different buffer sizes, copying "\0"s and copying from other buffers.
Printing *foo
, right after strcpy()
, sometimes prints random gibberish, sometimes exactly what I expect it, and sometimes nothing at all.
EDIT #1:
I was only able to quantify it to this:
Removing the strcpy()
call in function2()
, I see on gdb
that the *foo
variable has an address and value ("" @ 0x606420), but as soon as the function call returns, the pointer in the main function, points to 0x0
and that makes the next call to strcpy()
SegFault.
Trying to emulate the problematic function2()
doesn't work. The code in function2()
, while extensive, does not touch, at any moment, the parameter(after removing strcpy(), of course).