c - 正在释放的指针未分配给 C 中的字符串数组

标签 c pointers memory-management free dynamic-memory-allocation

我知道这个问题存在于其他地方,例如:

pointer being freed was not allocated in C error: pointer being freed was not allocated

但是,我还是很困惑。错误似乎与“修改 malloc 返回的原始指针”和“释放前 malloc 失败”之类的事情有关。我只是不明白这些原因如何适用于我的程序。

我正在写一个动态分配的字符串数组:

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

#define NLETTERS 25

typedef struct {
    char** array;
    size_t used;
    size_t size;
} array_t;

array_t* initArray(size_t initialSize) {
    array_t* a = malloc(sizeof(array_t));
    a->array = malloc(initialSize*sizeof(char*));
    a->used = 0;
    a->size = initialSize;

    int i;
    for(i = 0; i < initialSize; i++) {
        a->array[i] = malloc(sizeof(char) * NLETTERS);
    }

    return a;
}

void insertArray(array_t *a, char* element) {
    if (a->used == a->size) {
        a->size *= 2;

        a->array = realloc(a->array, a->size * sizeof(char*));

        int i;
        for(i = (int)a->used; i < a->size; i++) {
            a->array[i] = malloc(sizeof(char) * NLETTERS);
        }
    }
    a->array[a->used++] = element;
}

void freeArray(array_t *a) {
    int i;
    for(i = 0; i < a->size; i++) {
        free(a->array[i]);
    }

    free(a->array);
    free(a);
    a->array = NULL;
    a->used = a->size = 0;
}

void print_array(array_t *a) {
    int i;
    for(i = 0; i < a->size; i++) {
        printf("%s\n", a->array[i]);
    }
}

int main(int argc, const char * argv[]) {
    array_t *a;
    a = initArray(2);
    insertArray(a, "hello");
    insertArray(a, "how are you");
    print_array(a);
    insertArray(a, "yup");
    insertArray(a, "you know it");
    print_array(a);

    freeArray(a);

    return 0;
}

当我尝试“释放”时,出现错误:“未分配正在释放的指针” 就在

free(a->array[0]) 

在 freeArray() 中 for 循环的第一次迭代中;

帮助将不胜感激。

最佳答案

在你的代码中,通过说

  a->array[a->used++] = element;

您正在通过 malloc() 覆盖分配的内存,因此稍后将其传递给 free() 会导致问题。

相关,引用 C11,章节 §7.22.3.3,free 函数,(强调我的)

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

此外,稍后,这会导致 memory leak ,因为 malloc() 分配的内存实际上没有得到 free()-d。

解决方案:您应该使用 strcpy()将内容复制到分配的内存中。

关于c - 正在释放的指针未分配给 C 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40857626/

相关文章:

c - 海湾合作委员会错误 : string length too great (C11 type-generics)

c - 从单链表中删除元素

c - 读取不同流的独特功能

c - 初始化丢弃指针目标类型的限定符

c - 返回一个结构体类型

c - 将 int 视为地址/指针

c++ - 无法在函数 main() 中创建抽象类的指针

c - 为什么在访问阻塞/受限内存位置时不会出现段错误?

ios - UIWebView 内存泄漏。释放未使用资源的魔法是什么?

c++ - 我可以在 STL 容器中使用 MFC 对象吗?