简体   繁体   English

当我尝试重新分配()结构指针数组时,为什么我的 C 程序会崩溃?

[英]Why does my C program crash when I try to realloc() a pointer array of structs?

In the code below, I'm trying to expand an array of key value structs using realloc().在下面的代码中,我尝试使用 realloc() 扩展键值结构数组。

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

typedef struct {
    char key[25];
    char value[25];
} keyValPair;

void inputKeyVal(keyValPair* arr, int n) {
    char inputKey[25];
    char inputVal[25];
    printf("input key: ");
    scanf(" %24s", &inputKey);
    printf("input value: ");
    scanf(" %24s", &inputVal);
    n++;
    arr = (keyValPair*) realloc( (keyValPair*) arr, n*sizeof(keyValPair));
    strcpy(arr[n-1].key, inputKey);
    strcpy(arr[n-1].value, inputVal);
}

int main() {
    keyValPair initArr[] = {{"foo", "bar"}, {"a", "b"}};
    int n = sizeof(initArr)/sizeof(keyValPair);
    keyValPair* arr = malloc(n * sizeof(keyValPair));
    arr = initArr;
    inputKeyVal(arr, n);
}

Whenever I run it however, it runs up to the input prompt, before crashing at the realloc() attempt.但是,每当我运行它时,它都会运行到输入提示符,然后在 realloc() 尝试中崩溃。 I still can't figure out why or how to fix it.我仍然无法弄清楚为什么或如何解决它。 Fairly new to C, so a detailed explanation would be much appreciated and would go a long way.对 C 来说相当新,所以非常感谢详细的解释,并且 go 会有很长的路要走。

I think that there are three problems.我认为存在三个问题。

arr = initArr; overwrites the address of arr by initArr , so that realloc can't take the address which has been allocated by malloc .initArr覆盖arr的地址,这样realloc就不能取到malloc分配的地址。 To keep the address allocated by malloc , the contents of initArr should be copied into arr .为了保留initArr分配的地址,应该将malloc的内容复制到arr中。

#include <stddef.h>

for (size_t i = 0; i < sizeof(initArr) / sizeof(initArr[0]); i++) {
   arr[i] = initArr[i];
}

The last argument for scanf is wrong. scanf的最后一个参数是错误的。 & is unnecessary. &是不必要的。

scanf("%24s", inputKey);

After inputKeyVal , arr at main loses valid address because it is reallocated in inputKeyVal .inputKeyVal之后, mainarr丢失了有效地址,因为它在inputKeyVal中重新分配。 If you require the correct address which has been reallocated by realloc , inputKeyVal should return the reallocated address.如果您需要由realloc重新分配的正确地址, inputKeyVal应该返回重新分配的地址。

keyValPair* inputKeyVal(keyValPair* arr, int n) {
  /* snipped */
  return arr;
}

int main() {
  /* snipped */
  arr = inputKeyVal(arr, n);
  /* do something for arr */
  free(arr);
  return 0;
}

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

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