My program fails because of a segmentation fault. Using gdb i could see that the trouble was when i was initializing a 2d-array in my function.
My compiler flags were -Wall -Wpedantic -Wextra -Wconversion -std=gnu11
This is the function i'm using. The error raises on line 4. I don't understand why it breaks there, im fairly a beginner to C.
1 char ** get_categories_names(char * file_route, unsigned int maximum_categories) {
2 unsigned int category_counter = 0;
3
4 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
5 char * category = "";
6 FILE * categories_config;
7 categories_config = fopen(file_route, "r");
8
9 if (categories_config == NULL)
10 {
11 perror("Error while opening the file.\n");
12 exit(EXIT_FAILURE);
13 }
14
15 while (fgets(category, 255, categories_config) && category_counter < maximum_categories) {
16 printf("%d", category_counter);
17 categories_list[category_counter] = malloc(100 * sizeof(char));
18 category[strcspn(category, "\n")] = 0;
19 categories_list[category_counter] = category;
20 category_counter++;
21 }
22 fclose(categories_config);
23 return categories_list;
This is the gdb result:
(gdb) step
11 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) step
__GI___libc_malloc (bytes=40) at malloc.c:3028
3028 malloc.c: No existe el archivo o el directorio.
And this is the text file i was reading to:
horror
mystery
FPS
memes
comedy
malloc(). It'sfgets(category, 255, categories_config).categorydeclared is a pointer to a string literal"". You cant' overwrite that. Declare it aschar category[255}insteadcategories_list[category_counter] = category;You can't copy strings like that.