在我的程序中,我不明白我在哪里犯错。第一个指针缓冲区已损坏,其余缓冲区正常。 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
最佳答案
您正在溢出缓冲区:
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
砰,你死了。未定义的行为。
关于c - 为什么char双指针的第一项损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23913940/