Reputation: 31
I read tons of tutos and snippets, but I still don't understand why I get a segfault with this:
int fun(char **p) {
int i;
*p = malloc(2);
*p[0]=10;
*p[1]=20; // segfault NULL pointer
printf("fun()/n");
for (i=0; i<2; i++)
printf("%d ",*p[i]);
}
int main(int argc, const char *argv[])
{
char* buffer;
int i;
fun(&buffer);
printf("main()\n");
for (i=0; i<2; i++)
printf("%d ",buffer[i]);
return 0;
}
In gdb, it gives:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x0000000100000dea in fun (p=0x7fff5fbffab0) at test.c:10
10 *p[1]=20;
(gdb) p *p[0]
$1 = 10 '\n'
(gdb) p *p[1]
Cannot access memory at address 0x0
(gdb)
I have seen a lot of similar snippets, but there is surely something I am deeply misunderstanding.
Upvotes: 2
Views: 215
Reputation: 11
try returning the address of the same data type of the variable at the LHS. malloc() by default returns a void value. p = (char) malloc(2); this way compiler knows how many bytes it has to move the pointer to fetch new variable.
Upvotes: 0