Realloc导致应用程序崩溃
这个问题已经被问了很多次,但我已经(从我所能说的)完成了这里提到的所有事情。基本上,我每次从TCP套接字中获取一个字符,并用一个字符构建一个动态增长的字符串。我可以做循环打印,看到字符串不断增长,当它达到20个字符长时,程序崩溃Realloc导致应用程序崩溃,c,memory,crash,realloc,C,Memory,Crash,Realloc,这个问题已经被问了很多次,但我已经(从我所能说的)完成了这里提到的所有事情。基本上,我每次从TCP套接字中获取一个字符,并用一个字符构建一个动态增长的字符串。我可以做循环打印,看到字符串不断增长,当它达到20个字符长时,程序崩溃 while(FilterAmount != 0) { g_io_channel_read_chars (source,(gchar *) ScanLine,1,&BytesRead,&GlibError); printf("Scanlin
while(FilterAmount != 0)
{
g_io_channel_read_chars (source,(gchar *) ScanLine,1,&BytesRead,&GlibError);
printf("Scanline: %s FilterAmount: %ld\n", ScanLine, FilterAmount);
//the filters are delimited by \n, munch these off, reset important variables, save the last filter which is complete
if(ScanLine[0] == FilterTerminator[0]) {
//if the Filter Name actually has a filter in it
if(FilterName != NULL){
FilterArray = FilterName; //save off the filter name
printf("This is the filter name just added: %s\n", FilterName);
FilterArray++; //increment the pointer to point to the next memory location.
FilterAmount--; //update how many filters we have left
FilterNameCount = 0; //reset how many characters each filter name is
free(FilterName);
free(FilterTmp);
}
}
else {
printf("else!\n");
//keep track of the string length of the filter
FilterNameCount++;
//allocate more memory in the string used to store the filter name + null terminating character
FilterTmp = (gchar*)realloc(FilterName, FilterNameCount*sizeof(char) + 1);
if(FilterTmp == NULL)
{
free(FilterName);
printf("Error reallocating memory for the filter name temporary variable!");
return 1;
}
FilterName = FilterTmp;
printf("filter name: %s\n", FilterName);
//concat the character to the end of the string where space was just made for it.
strcat(FilterName, ScanLine);
}
}
}
这部分代码循环,每当我们在将数据读入的缓冲区中有一个非“\n”字符时循环。每次分配第21个字符的位置时,程序都会崩溃。以下是相关声明:
static gchar *FilterName = NULL, *FilterTmp = NULL;
static gchar ScanLine[9640];
空字符需要额外一个字节。另外:strcat假定原始字符串以null结尾。这不是,至少不是第一次。(realloc()不会将内存全部设置为零)@wildplasser很好,添加了一个字符就做到了。你真棒。现在它在别的地方坠毁了,但我会调查的!字符串被声明为NULL,所以strcat第一次出现时,从技术上讲,它不是以NULL结尾的吗?@wildplasser奇怪,现在当我释放FilterTmp,但不是FilterName时,它崩溃了……出于所有意图和目的,它们应该是完全相同的东西。从这里看不出来。(扫描线起源于何处?是否以NUL结尾?)和:对每个字符重新分配和strcat()一次有效地导致程序对每个读取的字符使用(N*N)/2运行时间。@wildplasser我更新了我的代码,以显示释放变量的位置。如果你能看一看,我会非常感激的。另外,把你的评论写进一个答案,这样我就可以相信你为我的第一个问题提供了解决方案!