0

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

idgit
  • 11
  • 3
  • Maybe this is an assignment for how to use malloc() but I would not malloc() here. And fscanf() is easy but not used in robust code any more since you cant supply the length. If you're on Windows use fscanf_s() – Yetti99 Sep 15 '21 at 00:20
  • Does this answer your question? [Ways to allocate memory in C](https://stackoverflow.com/questions/7662649/ways-to-allocate-memory-in-c) – Muhammedogz Sep 21 '21 at 06:37

1 Answers1

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273