如何在结构内部的数组中释放和写入NULL指针,间接通过指向struct的指针?

时间:2017-08-01 18:51:57

标签: c pointers recursion null children

我必须设置一个指针指向NULL的引用 但是函数{ "a":[ { "value1":"ab", "value2": 2 }, { "value1":"ab", "value2":2 } ] } 似乎不起作用,由输出表示 函数deleteP(...)delete()以某种方式工作,即使后者只用零填充内存(由数组中的指针指向)。 我希望数组中的指针最终为NULL,并且不起作用。

我需要通过指向结构的指针(在我的代码中为memoryset(),在fs->child[20]内部的本地指针变量)来做所有事情(即将el设置为NULL等)。这是因为我经常在deleteP(...)个孩子和他们的孩子之间进行迭代,很多次,我将当前孩子放在fs

我怎么解决?

el

输出:

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

#define HEIGHT 255
#define LENGTH 256
#define MAX_CHILDREN 1024

typedef struct FS FS;
typedef struct Elem Elem;

struct Elem {
    char name[LENGTH];
    char content[256];
    int isFile;
    int emptyCells;
    Elem *child[MAX_CHILDREN];
};

struct FS {
    int emptyCells;
    Elem *child[MAX_CHILDREN];
};

void delete(FS *fs){
    free(fs->child[20]);
    fs->child[20] = NULL;
}

void deleteP(FS *fs){
    Elem *el = calloc(1, sizeof (Elem));
    el = fs->child[20];
    free(el);
    el = NULL;
}

void memoryset(FS *fs){
    Elem *el = calloc(1, sizeof (Elem));
    el = fs->child[20];
    memset(el, 0, sizeof(Elem));
}

int main(int argc, const char * argv[]) {      

    FS *fs = calloc (1, sizeof(FS));
    fs->emptyCells = MAX_CHILDREN;
    fs->child[20] = calloc (1, sizeof(Elem));
    strcpy(fs->child[20]->name, "Hello");
    printf("No delete: %s\n", fs->child[20]->name);

    memoryset(fs);
    printf("MEMSET: %s\n", fs->child[20]->name);

    fs->child[20] = calloc (1, sizeof(Elem));
    strcpy(fs->child[20]->name, "Hello");
    delete(fs);
    printf("Delete: %s\n", fs->child[20]->name);

    fs->child[20] = calloc (1, sizeof(Elem));
    strcpy(fs->child[20]->name, "Hello");
    deleteP(fs);
    printf("DeleteP: %s\n", fs->child[20]->name);


}

1 个答案:

答案 0 :(得分:3)

请允许我用我的话说出你的目标 (在验证我在聊天中的理解之后):

  • 你想要释放存储在数组中的指针指向的内存, 它位于结构体内部,您可以获得指向
  • 的指针
  • 您无法直接访问阵列成员,
    只能通过指向包含结构的指针
  • 您还想将NULL写入数组成员
  • 查看你的代码,你试图通过制作数组成员的副本(这是一个指针)来做到这一点
  • 它主要起作用,只是数组成员不会最终为NULL (以及xing和BLUEPIXY提到的一些问题)

基本上,您需要一个指向数组成员的指针,而不是数组成员的副本。

所以你的功能应该是:

void deleteP(FS *fs){
    Elem **el; // pointer to pointer, instead of pointer (and no calloc)
    el = &(fs->child[20]); // pointer to array member
    free(*el); // free the pointer in the array member (not a copy of it),
               // though the effect is the same
    *el = NULL; // write NULL to the array member, not a copy of it,
                // this is what changes the effect to what you want 
}

如果我没有输错任何内容,这或多或少都是我们聊天的结果 据我了解,它解决了你的问题。欢呼声。

据我所知,这也应该修复xing deleteP(...)内部发现的内存泄漏 但请注意在memoryset(...)中修复它。

这不能解决BLUEPIXY发现的UB(未定义行为)问题。 为此,您需要重新编写调试打印,并确保不要取消引用已释放内存的任何指针(服务顺序问题),也不要取消引用任何设置为NULL的指针。

顺便说一句,这可以在没有本地指针变量的情况下完成;通过参数fs完成所有事情。但是我让解决方案更接近您自己的代码,以便更清楚地了解有什么区别。在我看来,通过本地指针进行操作的方式更具可读性。它甚至可能更快,但看到现代编译器有多好,我对此表示怀疑;实际的原因是清晰度和可读性。