haunted85
haunted85

Reputation: 1671

Substring extraction in C and segmentation fault

I have a string like this: word1;word2;42;word3- and I need to extract the words divided by the separators and store them in a struct that has the following structure:

typedef struct Info {
   char *info_one;
   char *info_two;
   char *info_three;
   int number;
} Info;

In order to get the words I have written this function:

char *get_words(char *source, char **dest, const char separator)
{
    int length;
    char *substring;

    substring = strchr(source, separator);
    length = strlen(source) - strlen(substring);
    (*dest) = (char *) malloc ((length+1) * sizeof(char));  
    strncpy(*dest, source, length);
    (*(dest + length)) = '\0';
    return substring+1;
}

and I call this function from main like this:

int main(int argc, char *argv[]) {
   Info *info;
   char *number;
   char *substring;
   char *stringinfo = "dog;cat;12;elephant-";

   info = (Info *) malloc (sizeof(Info));
   substring = stringinfo;

   substring = get_words(substring, &info->info_one, ';');
   substring = get_words(substring, &info->info_two, ';');
   // -------- 
   substring = get_words(substring, &number, ';');
   info->number = atoi(number);
   // --------
   substring = get_words(substring, &info->info_three, '-');

   return 0;
}

my problem is this code generates segmentation fault while processing the substring remaining after extracting the "number part". If I don't put a number in the string and, clearly, I don't call the function to extract it, everything runs smoothly. I can't figure out what is wrong, can you help me catch the bug?

Upvotes: 1

Views: 141

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You are using the local variable:

(*(dest + length)) = '\0';

must be

(*(*dest + length)) = '\0';

Upvotes: 2

Related Questions