我有一个带2D阵列的程序。首先,我像这样分配数组:
char **crossword;
crossword = (char **) malloc(n* sizeof(*crossword));
for (i = 0; i < n; i++)
crossword[i] = (char *)malloc(n);
n = 50。
然后我有函数,从stdin读取字符串。问题是,我不知道这些字符串将会有多少或多长。
void read(char **p,int *n)
{
char tmp = 0,prevtmp = 0;
int i = 0, j = 0,x;
while (1)
{
prevtmp = tmp;
tmp = getchar();
if ((tmp == '\n' && prevtmp == '\n') || feof (stdin))
{
*n = i;
break;
}
if (tmp == '\n')
{
p[i][j] = '\0';
i++;
if (i == *n)
{
p = (char **) realloc(p, 2*i); // if there is more strings than space for them, allocate more memory.
for (x = i; x < 2*i; x++)
p[x] = (char *) malloc (*n);
*n *= 2;
}
j = 0;
continue;
}
p[i][j] = tmp;
j++;
if (j == *n)
p[i] = (char *)realloc(p[i], 2*j); //same as above
}
}
函数被调用如下:
read(crossword,&n);
当不需要realloc时,此函数可以正常工作(少于50个字符串,每个字符串少于50个字符)。但是对于大输入,这会失败
*** glibc detected *** ./a.out: malloc(): memory corruption (fast): 0x00000000014282f0 *** error.
我认为我的问题是在我重新分配更多内存的部分,这里是从valgrind输出的:
==8885== Invalid write of size 1
==8885== at 0x40084C: read (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
==8885== by 0x40177F: main (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
==8885== Address 0x51f2b88 is not stack'd, malloc'd or (recently) free'd
==8885==
==8885== Invalid write of size 8
==8885== at 0x4008A6: read (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
==8885== by 0x40177F: main (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
==8885== Address 0x51f4f00 is not stack'd, malloc'd or (recently) free'd
valgrind: m_mallocfree.c:266 (mk_plain_bszB): Assertion 'bszB != 0' failed.
valgrind: This is probably caused by your program erroneously writing past the
end of a heap block and corrupting heap metadata. If you fix any
invalid writes reported by Memcheck, this assertion failure will
probably go away. Please try that before reporting this as a bug.
==8885== at 0x3804C6CF: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x3804C812: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x38000883: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x380574EA: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x38057E03: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x380212DC: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x3802146A: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x3808F656: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
==8885== by 0x3809E68C: ??? (in /usr/lib/valgrind/memcheck-amd64-linux)
sched status:
running_tid=1
Thread 1: status = VgTs_Runnable
==8885== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8885== by 0x4008A5: read (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
==8885== by 0x40177F: main (in /home/xerw/Dropbox/CVUT/PROGTEST/du6/a.out)
我一直在试用指针很短的时间,所以我不知道出了什么问题。我一直试图解决这个问题几个小时,但我没有想出任何东西。
我做错了什么?
答案 0 :(得分:1)
问题似乎在于以下几行:
p = (char **) realloc(p, 2*i);
我想它应该是:
p = (char **) realloc(p, (2*i)*sizeof(char*));
即。您希望增加数组以容纳2*i
元素,因此您需要分配2*i
次char*
的大小。