尝试释放二维数组时堆损坏错误

时间:2015-12-29 18:49:45

标签: c string free heap-corruption

我的程序收到一个二维的字符串数组。在它做它应该做的事情后,我尝试释放为字符串分配的内存,但是当我尝试这样做时,我得到了一个堆损坏错误。 这是我的代码:

printf("Please enter the number of lines:");
        scanf("%d", &length);
        lines = (char**)malloc(length*sizeof(char*));//allocating memory for the array of strings "lines".
        if (lines == NULL)
        {
            printf("Error! Not enough memory.");
            return 0;
        }
        getchar();//needed in order to use "gets".
        printf("Please enter your lines:\n");
        for (i = 0; i < length; i++)
        {
            printf("%d.", i);
            gets(buffer);//user inserts the string "buffer".
            lines[i] = (char*)malloc(strlen(buffer)*sizeof(char));//allocating memory for the strings in the array according to the ength of the string "buffer".
            if (lines[i] == NULL)
            {
                printf("Error! Not enogh memory.");
                return 0;
            }
            strcpy(lines[i], buffer);//copies the string "buffer" into "lines[i]".
        }
        printf("Plese enter your comparison string:");
        text = (char*)malloc(80 * sizeof(char) + 1);//allocating temporary memory for the string "text".
        gets(text);//inserting the string "text".
        text = (char*)realloc(text, strlen(text)*sizeof(char)+1);//reallocating the correct memory of "text" according to its exact length and adding an additional memory spot for the chat "\0".
        cmpresult = isEquivalent(lines, length, text);//calling the function
        if (cmpresult == TRUE)//if the function returned TRUE
            printf("The strings are equal.\n\n");
        else printf("The strings are not equal.\n\n");//if the function returned FALSE.
        for ( i = 0; i < length; i++)//free the memory allocated for lines[i].
            free(lines[i]);
        free(lines);//free the memory allocated for the array "lines".
        getchar(option);
    }

在重新调试之后,我发现这是崩溃我的程序的行。

for (i=0; i < length; i++)//free the memory allocated for lines[i].
 free(lines[i]);

我有一天到期而且我很绝望! 谢谢。

2 个答案:

答案 0 :(得分:1)

有几个问题:

  1. 您没有为字符串分配足够的内存。正如Weather Vane所说,C字符串是零终止的,你需要考虑到'0'并在每次为字符串分配位置时再分配一个字节。

  2. 请勿使用strcpy(),而是使用strncpy()。这是出于安全问题。请参阅Why should you use strncpy instead of strcpy?

  3. 出于同样的原因,请勿使用gets()

  4. text未被释放(这是您原来的问题)

答案 1 :(得分:1)

每行发生溢出:

gets(buffer);
lines[i] = (char*)malloc(strlen(buffer)*sizeof(char));
if (lines[i] == NULL)
{
    printf("Error! Not enogh memory.");
    return 0;
}
strcpy(lines[i], buffer); // <----- overflow happens here

要解决此更改:

lines[i] = (char*)malloc(strlen(buffer)*sizeof(char));

为:

lines[i] = (char*)malloc((strlen(buffer)+1)*sizeof(char));

以下代码中的realloc()对溢出没有帮助。到那时溢出已经发生(如果它发生)。

text = (char*)malloc(80 * sizeof(char) + 1);
gets(text); // <----- overflow happens here if string > 80
text = (char*)realloc(text, strlen(text)*sizeof(char)+1);