In the code below, I'm trying to expand an array of key value structs using 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. 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.
arr, but you never changemain's, so any use ofarrafter the call toinputKeyValwill be wrong.keyValPair* arr = malloc(n * sizeof(keyValPair)); arr = initArr;This is wrong, you're creating a memory leak. Afterarr = malloc(..),arrpoints to some memory (unlessmallocfails). When you doarr = initArr, you reassignarrto point toinitArr. Now, nothing points to the memory you just allocated, so it can't be used orfreed. Additionally as mentioned, nowarrpoints to non-reallocable memory.char inputKey[25]; .... scanf(" %24s", &inputKey);implies your are compiling without all warnings enabled. Save time, enable all warnings.