1

I have a program that parses a text file, and stores it in a pointer array. I have only one problem. I'm trying to store an array of strings in a char ** object, but whenever I assign a value to the char **, I get seg faults.

#include "database.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char **get_values(int recipe_num, char *file) {
    int placehold_num=recipe_num;
    char *text=parse_recipes(file);
    int num_recipes=count_recipes(file);
    char **array_strings;
    int index=-1;
    for (int i=0;*(text+i)!='\0';i++) {
        if (*(text+i)=='R' && *(text+i+1)=='e' && *(text+i+6)==':' && (text+i+7)==' ') {
            i+=13;
            index++;
            for (int j=0;*(text+i+j-1)!='\n';j++) {
                printf("%c",*(text+i+j));
                *(*(array_strings+index)+j)=*(text+i+j);
            }
        }

    }

}

This prints out the char I want from *(text+i+j), but seg faults on the next line. I'm extremely sure it isn't a problem with another function being called, I think it must be something with the way I'm dereferencing array_strings. Any help is greatly appreciated.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

The problem is in

*(*(array_strings+index)+j)=*(text+i+j);

You create a variable

char** array_strings;

It is now pointing to some garbage, you can see the current address just by calling

print("%p\n", array_strings);  

I strongly recommend to initialize array_strings by NULL, because once you can receive a pointer to memory, where you can write, and it will write to some place, where your other data can be stored, and you will just destroy both data. And if it is NULL you'll always receive segfault. So, at the moment you are trying to assign a value *(text+i+j) to a random place in the memory.

To do, what you want, you have to

char** array_strings = (char**)malloc(n * sizeof(char*));

where n is an amount of strings you need, and then in cycle do

array_strings[some_your_index] = text+i+j;

array_strings[some_your_index] is now char*, as text+i+j is.

Alex
  • 94
  • 9
  • See: [**Do I cast the result of malloc?**](http://stackoverflow.com/q/605845/995714) `char **array_strings = malloc (sizeof *array_strings);` is sufficient. You then need to allocate for each string, e.g. `array_strings[i] = malloc (strlen(str) + 1);` – David C. Rankin Oct 16 '17 at 21:33
  • Thank you for that article, really interesting. I can just use my `char*` pointers, to point the strings, separated, for example, by `\0` in the old big string. Also, for me it is more difficult to read `sizeof *array_strings` than `sizeof char*`, and I think it is not a problem to write like that – Alex Oct 16 '17 at 21:41