I'm new to C and currently learning how to dynamically allocate memory. Currently, I'm trying to create a dynamically allocated character array, where the memory for each individual string is also dynamically allocated. Each string is retrieved from a line in a txt file (numIngredients = number of lines | MAX_ING = maximimum number of characters per line/ingredient).
char** readIngredients(int numIngredients){
FILE *in;
in = fopen("input.txt", "r");
char** ingredients;
ingredients = (char**)malloc(numIngredients*sizeof(char));
for(int i=0; i<numIngredients; i ){
ingredients[i] = (char*)malloc(MAX_ING*sizeof(char));
}
for(int i=0; i<numIngredients; i ){
fscanf(in, "%s", ingredients[i]);
}
fclose(in);
return ingredients;
}
the segmentation fault seems to happen right when I declare ingredients... what am i doing wrong
CodePudding user response:
You're not allocating enough memory for an array of pointers:
ingredients = (char**)malloc(numIngredients*sizeof(char));
Instead, you allocate space for numIngredients
elements of size sizeof(char)
. This causes you to overrun allocated memory triggering undefined behavior.
Multiply by the size of a char *
instead, so:
ingredients = malloc(numIngredients*sizeof(char *));
Or even better:
ingredients = malloc(numIngredients*sizeof(*ingredients));
As it doesn't depend on the type of ingredients
.