错误释放char ***

时间:2015-01-14 15:57:37

标签: c arrays char malloc free

这是代码:

我知道这是什么问题,我试了好几个小时来解决它,但没有成功

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input(char ***array1,int * sizeWords,int size)
{
    for (int i = 0; i < size; i++)
    {
        char word[81] = "";
        char descrip[201] = "";
        int numAgdarot = 0;
        //how mach agdarot
        printf("how mach of agdarrot you want? ");
        scanf("%d", &numAgdarot);
        //save the count of agdarot
        sizeWords[i] = numAgdarot;

        do
        {
            printf("enter word number %d: ", i);
            _flushall();
            gets(word);
        } while (textSpace(word) == False);

        (array1)[i] = (char**)malloc(numAgdarot + 1 * sizeof(char*)); //set the num and agdarot

        //save the word
        (array1)[i][0] = (char*)malloc(strlen(word) * sizeof(char));
        strcpy(array1[i][0], word);
        //save the agdarot
        for (int j = 1; j <= numAgdarot; j++)
        {
            printf("enter descrip number %d: ", i);
            _flushall();
            gets(descrip);
            (array1)[i][j] = (char*)malloc(strlen(descrip) * sizeof(char));
            strcpy(array1[i][j], descrip);
        }
    }
}
int main() {
    int *sizeWords = NULL;
    int size = 0;
    char *x=NULL;// = "jk";

    char *** array1  = NULL;

    printf("enter number of word: ");
    scanf("%d", &size);
    array1 = (char***)malloc(size * sizeof(char**));
    sizeWords = (int*)malloc(size * sizeof(int));
    //x = temp(x,sizeWords);

    //input the word and agdarot
    input(array1, sizeWords, size);

    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < sizeWords[i] + 1; j++)
        {
            free(array1[i][j]);
        }
        free(array1);
    }

    return 0;
}

正常阻止后出现“HEAP CORRUPTION DELETED”错误。为什么? 如果我使用调试器,我会看到char *,但我不能免费...

2 个答案:

答案 0 :(得分:3)

否则

malloc(strlen(word) * sizeof(char));

几乎总是错误。请记住,字符串还包含strlen函数(终止符'\0')未报告的额外字符。这意味着您对strcpy的下一次调用会将写在分配内存的末尾。

你应该做的是为额外的终结者角色分配内存:

array1[i][0] = malloc(strlen(word) + 1);

[请注意,我更改了代码,首先是因为不需要array周围的括号,其次是因为in C one should not cast the return of malloc,第三是因为指定了sizeof(char) < / em> be 1。]

请务必在调用strlen时更改您使用malloc的所有其他地方。

答案 1 :(得分:0)

这些分配太小了:

(array1)[i][0] = (char*)malloc(strlen(word) * sizeof(char));
strcpy(array1[i][0], word);

// ...    
(array1)[i][j] = (char*)malloc(strlen(descrip) * sizeof(char));
strcpy(array1[i][j], descrip);

终止\0需要额外的字符。 strcpy()正在写入未分配的空间。

为自己省点麻烦,并且:

(array1)[i][0] = strdup(word);

// ...    
(array1)[i][j] = strdup(descrip);

而且,正如评论中指出的那样,

for (int i = 0; i < size; i++)
{
    for (int j = 0; j < sizeWords[i] + 1; j++)
    {
        free(array1[i][j]);
    }
    free(array1);
}

应该成为:

for (int i = 0; i < size; i++)
{
    for (int j = 0; j < sizeWords[i] + 1; j++)
    {
        free(array1[i][j]);
    }

    free(array1[i]);
}

free(array1);