我目前在C中编写我的第一个程序,来自C ++。我遇到了realloc的问题。
void addToBuffer(char c,char* buffer,int *bufferSize, int *numInBuffer, int* rightAfterSpace, int* numInSize, int* size, char** words)
{
if(*numInBuffer == *bufferSize)
{
int doub = 2 * (*bufferSize);
buffer = (char*) realloc(buffer,doub);
(*bufferSize) *= 2;
}
buffer[*numInBuffer] = c;
(*numInBuffer)++;
if(c==' ') {
*rightAfterSpace =1;
}
}
int main()
{
char* buffer;
buffer = (char*)malloc(10);
int bufferSize = 10;
int numInBuffer =0;
char** words;
words = (char**)malloc(10*sizeof(char*));
int wordsSize = 10;
int numInWords =0;
int *size;
size = (int*)malloc(sizeof(int));
int currentSize = 0;
int sizeSize = 2;
int numInSize=0;
//Update every time a value is put into words.
int numOfRecords = 0;
char c;
int rightAfterSpace = 1;
//Get rid of any opening spaces
c = getchar();
while(c == ' ')
{
c =getchar();
}
while(c!=EOF){
addToBuffer(c, buffer, &bufferSize, &numInBuffer, &rightAfterSpace, &numInSize, size, words);
currentSize++;
c = getchar();
}
//...more code in main
我注释了部分代码,以验证他们没有对此问题做出贡献。在粘贴代码之前,我删除了那些注释掉的行,以防它分散注意力。我已多次浏览此代码,但无法找到错误。 Realloc可以正常重新分配20,然后是40个字节,但一旦达到80,我就会遇到错误。 Valgrind给了我以下信息,但我不确定如何解释它。
==21051== Memcheck, a memory error detector
==21051== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==21051== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==21051== Command: ./s
==21051==
==21051== Invalid write of size 1
==21051== at 0x400920: addToBuffer (in /w/home.11/cs/ugrad/t/Documents/CS35L/week5/s)
==21051== by 0x400B33: main (in /w/home.11/cs/ugrad/t/Documents/CS35L/week5/s)
==21051== Address 0x4c3b04b is 1 bytes after a block of size 10 free'd
==21051== at 0x4A06C20: realloc (vg_replace_malloc.c:662)
==21051== by 0x4008E1: addToBuffer (in /w/home.11/cs/ugrad/t/Documents/CS35L/week5/s)
==21051== by 0x400B33: main (in /w/home.11/cs/ugrad/t/Documents/CS35L/week5/s)
==21051==
==21051==
任何帮助都会非常感激。