【问题标题】:malloc(): smallbin double linked list corruptedmalloc(): smallbin 双链表损坏
【发布时间】:2015-11-20 16:08:25
【问题描述】:

此代码在运行时在 else 中生成错误:

不存在 *** `./a.out' 中的错误:malloc(): smallbin 双链表已损坏:0x09faed58 *** 中止(核心转储)

bool fileExists(char *file) {
    if (access(file, F_OK) != -1) {
        return true;
    } else {
        return false;
    }
}

void CopyPaste() {
   char *fileName = basename(path);
   char *c = strcat(dest, "/");
   char *newPath = strcat(c, fileName);

   if (fileExists(newPath)) {
       printf("exists\n");
   } else {
       printf("non exists\n");
   }
}

如果我像这样更改连接代码:

char *newPath = strcat(strcat(dest,"/"),fileName);

它会产生这个不同的错误:

`./a.out' 中的错误:损坏的双链表

可能是什么问题?

【问题讨论】:

  • 您的工作环境如何?
  • ubuntu,使用gtk库的C程序
  • 你有什么问题?
  • 我找不到问题并解决它!!!!
  • strcat 将第二个参数复制到第一个给定的缓冲区。 strcat(dest, "/")strcat(strcat(dest, "/"), fileName); 看起来很可疑。 dest 在哪里以及如何定义? (顺便说一句,您真的应该在 Google 上搜索“C 格式约定”并遵循其中的一些原则。您的代码很难阅读。)

标签: c


【解决方案1】:

您似乎没有正确使用strcat。您的代码似乎假设连接发生在strcat 为您内部分配的新缓冲区中,但事实并非如此。 strcat 实际上修改了第一个参数指向的缓冲区,并将第二个缓冲区的内容附加到第一个。

根据manual

strcat() 函数将src 字符串附加到dest 字符串, 覆盖dest末尾的终止空字节('\0'),以及 然后添加一个终止空字节。字符串不能重叠,并且 dest 字符串必须为结果留出足够的空间。如果dest 是 不够大,程序行为不可预测;缓冲区溢出 是攻击安全程序的常用途径。

在你的情况下:

char *dest; dest =  gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog));

将根据来自gtk_file_chooser_get_current_folder 的返回设置dest,它返回一个保存文件夹名称的缓冲区。该缓冲区没有额外的空间供您追加。如果您想添加(追加)到该函数调用的结果,您需要分配一个单独的缓冲区来保存该文件名称加上您想要附加的任何内容。

char *new_dest = malloc(SIZE_YOU_NEED);

strcpy(new_dest, dest);   // Copy file name from gtk_file_chooser_get_current_folder
strcat(new_dest, "/");
strcat(new_dest, fileName);

在这种情况下,您可以将最后两行快捷方式为:

strcat(strcat(new_dest, "/"), fileName);

因为根据手册,strcat 将第一个参数指针作为返回值返回给您。

【讨论】:

  • 它现在可以工作了,非常感谢,我不知道 strcat 将结果放在第一个参数中
  • @Faceopace 很高兴它有效。这就是为什么在使用以前没有使用过的功能之前查看手册很重要的原因。它们通常不会按照您认为应该的方式工作。 :)
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 2013-11-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2016-07-01
相关资源
最近更新 更多