简体   繁体   中英

Issue with C double pointer allocation

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.

You mean (*p)[1] . What you said is *(p[1]) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM