我阅读了大量的 tutos 和片段,但我仍然不明白为什么会出现段错误:
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;
}
在 gdb 中,它给出:
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)
我看过很多类似的片段,但肯定有一些我深深误解的东西。