简体   繁体   English

调用free方法时出现分段错误(核心转储)错误

[英]Segmentation fault (core dumped) error when free method is called

I m trying to free the memory space for an array of char: 我正在尝试为char数组释放内存空间:

        static void cleanArray(char* array)
                {
                    int i;
                    int size = strlen(array) + 1;
                    for(i = 0; i < size; i++)
                        free(array[i]);
                    free(array);
                }

    int main(){
    char* array = (char *)malloc(1 * sizeof(char*));
    int c;
    for(c=0;c<100;c++){         //code to populate some string values in the array.
    void *p = realloc(array, (strlen(array)+strlen(message)+1)*sizeof(char*));
    array = p;
    strcat(array, "some string");
    }

cleanArray(array);           //I get error only when I call this method.
    }

But for the above code I m getting Segmentation fault error. 但是对于以上代码,我遇到了Segmentation fault错误。

And when I just try the following code instead of cleanArray() I dont think the array is freed up: 当我只尝试以下代码而不是cleanArray()时,我不认为该数组已释放:

    free(array);
printf("%s",array); //it prints all the values in the array. Hence, I concluded it is not freedup.

Line free(array[i]); free(array[i]); in loop have problem. 循环中有问题。 array[i] is a char value(which is actually int by integer promotion) and passing that value to free will be considered as pointer. array[i]是一个char值(通过整数提升实际上是int),并将该值传递给free将被视为指针。 Now you are trying to free that address about which you do not have any idea. 现在,您正在尝试释放对该地址不了解的地址。

There are multiple problems: 存在多个问题:

  1. You don't need to call free() on each character of the string. 您不需要在字符串的每个字符上调用free() Just call free(array) . 只需调用free(array)
  2. sizeof(char*) in malloc() and realloc() is incorrect. malloc()realloc() sizeof(char*)不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM