malloc():smallbin双链表损坏

时间:2015-11-20 16:08:25

标签: c

此代码在运行时在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':损坏的双链表

出错

问题可能是什么?

1 个答案:

答案 0 :(得分:3)

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

根据manual

  

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

在你的情况下:

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

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

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将第一个参数指针返回给你作为返回值。