为什么char双指针的第一项是腐败的

时间:2014-05-28 14:07:03

标签: c pointers

在我的节目中,我不明白我在哪里弄错了。第一个指针缓冲区正在破坏剩余的缓冲区。 Gcc版本是“gcc(Ubuntu / Linaro 4.6.3-1ubuntu5)4.6.3”。 请帮忙... 谢谢。

代码:

#include <stdio.h>

main()
{
  char **buff;

  int i = 0;
  buff = (char **) malloc(sizeof(char *));

  for(i = 0; i < 10; i++)
  {
    buff[i] = (char *) malloc(sizeof(char) * 32);
    sprintf(buff[i], "test %d",i); 
  }

  printf("address of buff: %u\naddress of buff[0]: %u\n", buff, buff[0]);
  for(i = 0; i < 10; i++)
  {
    printf("%d: %u:%s\n", i, buff[i], buff[i]); 
  } 

}

我的输出:

address of buff: 21930000
address of buff[0]: 21930032
0: 21930032:��N
1: 21930080:test 1
2: 21930128:test 2
3: 21930176:test 3
4: 21930224:test 4
5: 21930272:test 5
6: 21930320:test 6
7: 21930368:test 7
8: 21930416:test 8
9: 21930464:test 9

1 个答案:

答案 0 :(得分:0)

你正在超越你的缓冲区:

buff = (char **) malloc(sizeof(char *)); // a single char* is allocated
for(i = 0; i < 10; i++)
{
    buff[i] // when i is 1 it's out of bounds
砰,你死了。未定义的行为。