【问题标题】:struct with ptr array to nested structs assignment and mem allocation带有 ptr 数组的结构到嵌套结构分配和内存分配
【发布时间】:2017-07-26 18:33:28
【问题描述】:

我有一个结构,其中包含深度嵌套的 ptrs 到也包含指针的相关结构。我在正确初始化时遇到问题,因为 ptrs 数组的大小必须传递给 init 函数。见以下代码:

类型定义:

typedef struct tuple Tuple;
typedef struct dict Dict;
int findKey(Dict *d, char *check);

struct tuple {
    char                   *key;           //named loc
    void                   *val;           //data
};

struct dict {
    unsigned int           size;           //max size
    unsigned int           counter;        //# tuples
    Tuple                  **entries;     //list of tuples
};

初始化函数:

Dict *initDict(const unsigned int size) {
    Dict data = {.size = size, .counter = 0, .entries = (Tuple**) malloc(sizeof(Tuple*) * size)};
    for (unsigned int i = 0; i < size; i++) {
        data.entries[i] = (Tuple*) malloc(sizeof(Tuple));
        data.entries[i]->key = '\0'; /* initially null */
        data.entries[i]->val = '\0'; /* initially null */
    }
    Dict *d = (Dict*) malloc(sizeof(Dict));
    d = &data;
    return d;
}

字典操作:

short setTuple(Dict *d, char *key, void* val) {
    int i;
    if ((i = findKey(d, key)) != -1) { /* found key */
        d->entries[i]->val = val;
        return 0;
    }
    else {  /* new entry */
        if (d->counter < d->size) { /* find first null */
            for (unsigned int i = 0; i < d->size; i++) {
                if (d->entries[i]->key == NULL) break;
            } /* then replace null slot */
            d->entries[i]->key = (char *) malloc(sizeof(char) * strlen(key));
            d->entries[i]->key = key;
            d->entries[i]->val = (void *) malloc(sizeof(&val));
            d->entries[i]->val = val;
            d->counter++;
            return 0;
        }
        return -1; /* no room */
    }
}

short setTuples(Dict *d, char *json) {

}

void* getTuple(Dict *d, char *key) {
    int i;
    if ((i = findKey(d, key)) != -1) {
        void *val = d->entries[i]->val;
        return val;
    } return (void *) -1; /* not found */
}

void* getIndex(Dict *d, unsigned int index) {
    if (index < d->counter && d->entries[index]->key != NULL) {
        void *val = d->entries[index]->val;
        return val;
    } return (void *) -1; /* not found */
}

/* TODO: add checks for NULL ptr prior to freeing? */
int removeTuple(Dict *d, char *key) {
    int i;
    if ((i = findKey(d, key)) != -1) {
        free(d->entries[i]->key);
        free(d->entries[i]->val);
        free(d->entries[i]);
        d->entries[i]->key = '\0';
        d->entries[i]->val = '\0';
        d->counter--;
        return 0;
    } return -1; /* no room */
}

void destroyDict(Dict *d) {
    for (unsigned int i = 0; i < d->counter; i++) {
        free(d->entries[i]->key);
        free(d->entries[i]->val);
        free(d->entries[i]);
        d->entries[i]->key = '\0';
        d->entries[i]->val = '\0';
        d->entries[i] = '\0';
        d->counter--;
    }
    free(d->entries);
    free(d);
}

/* return index of tuple in dict or -1 if DNE */
int findKey(Dict* d, char* check) {
    unsigned int i;
    for (i = 0; i < d->counter; i++) {
        if (d->entries[i]->key != NULL && strcmp(d->entries[i]->key, check) == 0) {
            return i;
        }
    } return -1; /* not found */
}

【问题讨论】:

  • 你有什么问题?请发布minimal reproducible example,而不是您的整个代码
  • 始终相关:Please see this about casting the result of malloc。您也不会检查 malloc 是否成功。
  • 很好奇,谁或什么文字建议(Tuple*) 转换为data.entries[i] = (Tuple*) malloc(sizeof(Tuple));
  • d-&gt;entries[i]-&gt;key = (char *) malloc(sizeof(char) * strlen(key)); d-&gt;entries[i]-&gt;key = key; 内存分配不足,在第二次分配中丢失。可能想要memcpy/strcpy
  • d = &amp;data; --> *d = data; 我建议Tuple **entries; --> Tuple *entries;

标签: c pointers struct initialization


【解决方案1】:
Dict *initDict(const unsigned int size) {
    Dict data = { /*...*/ };
    // ...
    Dict *d = (Dict*) malloc(sizeof(Dict));
    d = &data;
    return d;
}

这里存在两个明显的问题:

  1. d = &amp;data; 会立即泄漏您使用 malloc 分配的内存。
  2. return d; 从 (1) 继续,您返回一个局部变量的地址。因此,您的程序行为是未定义的。

如果你想用你在局部变量中设置的值复制初始化新分配的内存,那就是需要取消引用的指针,然后分配指针:

Dict *initDict(const unsigned int size) {
    Dict data = { /*...*/ };
    // ...
    Dict *d = malloc(sizeof(Dict));
    if(d)
      *d = data;
    else {
      // Everything you allocated for data must be cleaned here.
    }
    return d;
}

我还添加了一个检查,当您的原始代码使用 malloc 时,您会非常想念。检查指针是否为 NULL!

【讨论】:

  • 我完全错过了那里的错误检查,感谢您指出这一点
【解决方案2】:

只是想发布我的实现来完善这个问题。实际上,我采用了一种更动态的方法,使用 2 个单独的“块”,其中一个保存表数据,另一个块保存我的 ptr 数组。以这种方式链接数据允许动态操作和职责分离/冗余、灵活性,更不用说不创建与重新分配内存的依赖关系。 @teppic 在这里有一个惊人的演练:dynamic ptrs to structs 也是如此。

编辑:我添加了一些代码清理(遗漏了一些旧语句)以及一些表的数据隐藏/抽象,现在所有测试都成功了,享受吧!

声明:

typedef struct tuple Tuple;
typedef struct dict Dict;
int findKey(Dict *d, char *check);

struct tuple {
    char                   *key;           //named loc
    void                   *val;           //data
};

struct dict {
    unsigned int           size;           //max size
    unsigned int           counter;        //# tuples
    Tuple                  *table;         //table of tuples
    Tuple                  **entries;      //arr of ptrs
};

初始化:

Dict *initDict(const unsigned int size) {
    Dict *d = (Dict *) malloc(sizeof(Dict));
    if (d) {
        d->size = size;
        d->counter = 0;
        d->table = malloc(sizeof(Tuple*) * size);
        d->entries = malloc(sizeof(Tuple*) * size);

        if (d->table && d->entries) {
            for (unsigned int i = 0; i < size; ++i) {
                d->entries[i] = d->table + i;
            }
            return d;
        }      /*       Failed to init:      */
        else { /* Data must be cleaned here. */
            free(d->entries);
            free(d->table);
            free(d);
        } exit(-1); /* fall through */
    } exit(-1);  /* fail safe */
}

setTuple(固定:o)

short setTuple(Dict *d, char *key, void* val) {
    int i;
    if ((i = findKey(d, key)) != -1) { /* found key */
        d->entries[i]->val = val;
        return 0;
    }
    else {  /* new entry */
        if (d->counter < d->size) { /* find first null */
            unsigned int i = 0;     /*   reset   */
            for (i; i < d->size; i++) {
            /* getting segv on break statement? */
                if (! d->entries[i] || ! d->entries[i]->key) break;
            } /* then replace null slot */
            d->entries[i]->key = key;
            d->entries[i]->val = val;
            d->counter++;
            return 0;
        } /* no room left in dict */
    } return -1;
}

还有一些其他的,但为了简洁......这里是内存清理:

int removeTuple(Dict *d, char *key) {
    int i;
    if ((i = findKey(d, key)) != -1) {
        d->entries[i]->key = '\0';
        d->entries[i]->val = '\0';
        d->counter--;
        return 0;
    } return -1; /* no room */
}

void destroyDict(Dict *d) {
    for (unsigned int i = 0; i < d->counter; i++) {
        d->entries[i] = '\0';
        d->counter--;
    }
    free(d->entries);
    free(d->table);
    free(d);
}

一旦块被释放然后就是这样,链表 FTW :) 请注意,在 dict 中实现的计数器也提供了在执行“get”元组时进行检查的参考。除了将字段显式设置为 null 外,还可以更快地搜索我们知道不会有我们想要的键的键(类似于“黑名单”)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多