【问题标题】:malloc.c:2451: sYSMALLOc Assertion failed in Cmalloc.c:2451:C 中的 SYSMALLOc 断言失败
【发布时间】:2013-02-11 02:41:17
【问题描述】:

我不断收到此错误vidprocess: malloc.c:2451: sYSMALLOc: Assertion (old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.

在这一步我只释放一次内存:

DIR *dp;
struct dirent *ep;     
dp = opendir (folder_input);
if (dp != NULL) {
    while ( (ep = readdir (dp)) && MAXVIDS != 0 ) {
        char *filename;
        filename = malloc(sizeof(char) * strlen(ep->d_name));
        strcpy(filename, ep->d_name);
        int len = strlen(filename);
        char *last_three = &filename[len-3];
        char trailer_file_name[100];
        int in_if = 0;
        if (strcasecmp(last_three, "MOV")  == 0) {
            strcpy(trailer_file_name, ep->d_name);
            MAXVIDS--;
            in_if = 1;
        }
        else if (strcasecmp(last_three, "MP4")  == 0) {
            strcpy(trailer_file_name, ep->d_name);
            MAXVIDS--;
            in_if = 1;
        }
        free(filename);

这是我唯一使用free() 的地方。如果我不使用这部分,我不会收到上面的错误,所以我只是假设由于内存释放而出现错误,但我不明白为什么这是错误的?

【问题讨论】:

    标签: c memory-management malloc free


    【解决方案1】:

    你没有为filename分配足够的内存:

        filename = malloc(sizeof(char) * strlen(ep->d_name));
    

    这不会为终止的空字节分配空间,您需要strlen(ep->d_name) + 1 字节。另外,作为旁注,sizeof(char) == 1 总是

    此外,对于此类错误,一个好的内存调试器可以为您节省大量时间。如果您的平台/arch 或其他类似工具可用,我建议使用类似 valgrind 的工具。

    通过溢出分配的缓冲区,您可能会损坏 malloc() 用于记账的内部数据结构,这就是您在 free() 中看到崩溃的原因。

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多