双重免费或腐败(!prev),一个malloc()和一个free()循环

时间:2015-10-01 22:30:51

标签: c free

我正在通过编写string.h lib的函数来练习C.但我现在遇到了一个我不明白的问题。当我执行我的程序时,它会崩溃并显示以下消息:

  

双重免费或腐败(!prev)

我尝试使用Valgrind,但似乎没有发生错误。

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char * duplicateString(const char * str) {
    size_t strLength = strlen(str);

    char * duplicatedString = malloc(strLength);
    if(duplicatedString == NULL)
        exit(EXIT_FAILURE);

    // +1 to copy '\0'
    strncpy(duplicatedString, str, strLength + 1);

    return duplicatedString;
}

void test_duplicateString()
{
  const char * src = "abc";
  char buf[1024];
  int i, j;
  char * temp = duplicateString(src);

  assert((strcmp((src),(temp)) == 0));
  assert(src != temp);
  free(temp);

  for(i = 0; i < 1024; ++i)
  {
    for(j = 0; j < i; ++j)
      buf[j] = (char) ('a' + (j % 26));
    buf[i] = '\0';

    temp = duplicateString(buf);
    assert((strcmp((buf),(temp)) == 0));
    free(temp);
  }
}

int main()
{
    test_duplicateString();
    return 0;
}

根据GDB,当i = 136时,该错误总是发生在第38行。 例如,为什么在i = 136,而不是之前?

#0  0x00007ffff7a6a5f8 in raise () from /usr/lib/libc.so.6
No symbol table info available.
#1  0x00007ffff7a6ba7a in abort () from /usr/lib/libc.so.6
No symbol table info available.
#2  0x00007ffff7aa905a in __libc_message () from /usr/lib/libc.so.6
No symbol table info available.
#3  0x00007ffff7aae9a6 in malloc_printerr () from /usr/lib/libc.so.6
No symbol table info available.
#4  0x00007ffff7aaf18e in _int_free () from /usr/lib/libc.so.6
No symbol table info available.
#5  0x000000000040093e in test_duplicateString () at /media/sf_data/Cours/Polytech/DI3/Langage_C/DoubleFreeTest/main.c:38
        src = 0x400a10 "abc"
        buf = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef\000\344\377\367\377\177\000\000\240\345\377\377\377\177\000\000x\030\375\367\377\177\000\000\000\000\000\000\000\000\000\000\230\331\377\367\377\177\000\000`\346\377\377\377\177\000\000?M\336\367\377\177\000\000\001\000\000\000\000\000\000\000"...
        i = 136
        j = 136
        temp = 0x602010 "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef"
        __PRETTY_FUNCTION__ = "test_duplicateString"
#6  0x0000000000400979 in main () at /media/sf_data/Cours/Polytech/DI3/Langage_C/DoubleFreeTest/main.c:44
No locals.

1 个答案:

答案 0 :(得分:1)

要将所有注释所说的内容放到答案中,在函数duplicateString()中,您没有分配足够的内存来使字符串符合空字符。< / p>

所以当你这样做时

strncpy(duplicatedString, str, strLength + 1);

你复制的内容超过缓冲区可以容纳的数量。解决方案显然是将缓冲区大小增加1。

char * duplicatedString = malloc(strLength + 1);