【问题标题】:Stack Smashing Detected - Aborted (core Dumped)检测到堆栈粉碎 - 中止(核心转储)
【发布时间】:2017-07-12 11:37:30
【问题描述】:

我似乎无法找到为什么这是堆栈粉碎,该代码旨在读取某些文件,读取每一行并在最后查找其他行。但我在代码的最后得到一个堆栈粉碎检测到的错误。

有什么想法吗?

代码是:

void main (int argc, char *argv[])
{

char lineCount;
int count = 0;
size_t buffer_size = 40;
char *buffer =malloc(buffer_size * sizeof(char));
char *buffer2 =malloc(buffer_size * sizeof(char));
char *buffer3 =malloc(buffer_size * sizeof(char));
char *buffer4 =malloc(buffer_size * sizeof(char));
FILE *Dictionary, *Names;
Dictionary = fopen ("/home/overdog/Documents/Coding/dictionary.txt","r");
Names = fopen ("/home/overdog/Documents/Coding/rawnames.txt","r");
    while(-1 != getline(&buffer,&buffer_size,Dictionary))
    {
        count = count + 1;

        for (int i =1; i <= 10; i++)
        {
            memcpy(buffer2,buffer,buffer_size);
            char num[1];
            RemoveEndLine(buffer2);
            sprintf(num,"%d",i);
            strcat(buffer2,num);
            printf("%s\n",buffer2);
                while(-1 != getline(&buffer3,&buffer_size,Names))
                {
                    memcpy(buffer4,buffer2,buffer_size);
                    printf("before break\n");
                    strcat(buffer4,buffer3);
                    printf("%s",buffer4);




                }


        }



    }
printf("Lines = %d \n",count);
free(buffer);
free(buffer2);
free(buffer3);
free(buffer4);
fclose(Dictionary);
fclose(Names);
printf("test\n");
}

输出似乎没问题,并且打印出代码末尾的"test"。然后看到 Stack smasting 错误。

【问题讨论】:

  • 因为您正在将可能有 40 个字符长的字符串连接到一个 40 个字符长的缓冲区中,所以您正在寻找麻烦。
  • "如果缓冲区不够大,无法容纳行,getline() 会使用 realloc 调整其大小,并根据需要更新 *lineptr 和 *n。"
  • @PaulOgilvie 好的。不过,strcat 部分仍然是一个问题,但真正的问题在于下面的答案。
  • @Jean-FrançoisFabre,完全同意。这里有很多问题。
  • 虽然 40 个字符可以读一个数字每行...

标签: c


【解决方案1】:

让我们仔细看看这两行:

char num[1];
...
sprintf(num,"%d",i);

您将 num 声明为 单个 字符的数组,忘记了 C 中的 (char) 字符串实际上称为 null 终止 字节字符串。这意味着单个字符的字符串需要 两个 char 元素的空间,以适应终止符。

由于您没有用于终止符的空间,因此 sprintf 将写入 超出范围 的数组,从而导致 未定义的行为 和您的堆栈崩溃。

如果您确定该数字永远不会超过一个数字(它不会,它将包括两位数字 10),那么您需要有一个至少包含两个字符元素的数组。

我还建议您使用snprintf 来避免类似的缓冲区溢出。

【讨论】:

    【解决方案2】:

    感谢所有帮助,Some Programmer Dude 所说的确实对我有所帮助,但我仍然遇到问题。我发现问题出在这条线上

    strcat(buffer4,buffer3);
    

    由于两者的缓冲区大小相同,它正在创建一个需要 80 缓冲区的字符串?

    我修改了行

    char *buffer4 =malloc(buffer_size * sizeof(char));
    

    阅读

    char *buffer4 =malloc(80 * sizeof(char));
    

    这现在可以在没有堆栈粉碎的情况下工作

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2021-08-26
      • 2021-07-18
      • 1970-01-01
      • 2021-10-10
      • 2012-07-01
      相关资源
      最近更新 更多