c - Realloc 结构数组作为函数参数产生段错误?

标签 c arrays struct realloc

在询问之前,我已经搜索了很多,但我似乎无法让这个功能发挥作用。
我有这个 array of structs 和 2 个字符串 (char*) 以及添加新结构的函数 put()
除非键已经存在,否则它只会用新值覆盖当前值。

尽管我在函数中通过引用传递数组并且没有制作本地副本,但内存仍然损坏(段错误).

源代码是在 Ubuntu 15.10 和最新版本的 gcc 下编译的。
在此先感谢您的帮助!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 3

struct store{
    char *key;
    char *value;
};

void put(char *key, char *value, struct store **store, int size){
    int i, found;
    struct store *temp = realloc(*store, (size + 1) * sizeof(struct store));
    for(i = 0; i < size; ++i){
        if(strcmp(key, store[i]->key) == 0){ //Key found, overwrite new value.
            store[i]->value = strdup(value); //Assume that every value is null terminated
            found = 1;
            break;
        }
    }
    if(found) return;

    *store = temp;
    if(!store){ 
         perror("realloc failed");
         exit(EXIT_FAILURE);
    }    
    store[size]->key = strdup(key); //New element
    store[size]->value = strdup(value);
    return;
}

int main(){
    int i = 0;
    struct store *store = malloc(N * sizeof(struct store));
    if(!store){ 
       perror("malloc failed");
       exit(EXIT_FAILURE);
    }
    store[0].key = strdup("123a");
    store[1].key = strdup("456b");
    store[2].key = strdup("789c");
    store[0].value = strdup("John");
    store[1].value = strdup("Sam");
    store[2].value = strdup("Mary");

    for(i = 0; i < N; ++i)
        printf("%s, %s\n\n",store[i].key,store[i].value); //This works fine

    put("123a","Jim",&store,N);
    for(i = 0; i < N; ++i)
        printf("%s, %s\n\n",store[i].key,store[i].value);

    put("653a","Tom",&store,N);
    for(i = 0; i < N+1; ++i)
        printf("%s, %s\n\n",store[i].key,store[i].value);

    return 0;
}

最佳答案

struct store *temp = realloc(*store, (size + 1) * sizeof(struct store));
for(i = 0; i < size; ++i){
    if(strcmp(key, store[i]->key) == 0){ //Key found, overwrite new value.
        store[i]->value = strdup(value); //Assume that every value is null terminated
        found = 1;
        break;
    }
}
if(found) return;

*store = temp;

如果找到 key ,则不要将 temp 分配给 *storerealloc 可以将分配的内存移动到一个全新的地址,从而使 *store 成为悬空指针。而且您确实还应该检查 temp 是否也不为 null。

还有你滥用store的问题。 store 是您传递给函数的指针的地址,而不是数组的第一个元素。

您需要像这样索引数组 (*store)[i]

关于c - Realloc 结构数组作为函数参数产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42868738/

相关文章:

c++ - 将仿函数作为函数指针传递

c - 如何使用相同的函数对 C 中的字符串进行 XOR 加扰并再次加扰?

c++ - 线程安全和 block 写入大小

json - 将 Coldfusion json 转换为 struct

c++ - 结构和 union

c# - 用于在构建期间将 C 枚举和常量脚本编写到 C# 的工具

c - 使用指定的初始值设定项来初始化结构中的二维字符数组初始值设定项会在 VS2013 中发出错误 C2078

c++ - std::array 类的堆栈溢出

java - 如何使用扫描仪从文本文件创建数组?

swift - Swift 中的哪些值类型支持写时复制?