Christian
Christian

Reputation: 311

strsep() causes segfault - why?

I am a little bit confused about pointer-of-pointer-const-var-string-char ;) Her's my code:

char* str_get_var(char *string,char delim)
{
        char    *found,
                *found2,
                *teststring;

printf("var string: %s\t",string);
teststring=strdup(string);
printf(" ---- var teststring: %s\n",teststring);

string=strdup(teststring);

found = strsep(&teststring,&delim);
printf("teststring \t var found: %s\n",found);
found2 = strsep(&string,&delim);
printf("string \t\t var found2: %s\n",found2);

return found;
}


int main(int argc, char *argv[])
{
char *message;
char trenner;
char *gefun;

message="ehzg=1";
trenner = '=';

printf("Start\n");
gefun=str_get_var(message,trenner);
printf("Ende\n");
return(0);
}

The programm produces the following output:

Start
var string: ehzg=1       ---- var teststring: ehzg=1
teststring       var found: ehzg
string           var found2: ehzg
Ende

As you might see from the code I would say the strdup to teststring is not needed as I would expect I can use the *string directly. However, as soon as I comment the following line I am getting a SegFault:

\\string=strdup(teststring);

Her's the output when commented out:

Start
var string: ehzg=1       ---- var teststring: ehzg=1
teststring       var found: ehzg
Speicherzugriffsfehler

So my question(s): How can I use *string directly for strsep? Why do I get a segfault when not doing strdup with the same content?

(BTW: Coding on Raspbian, if important).

Thanks! /knebb

Upvotes: 1

Views: 165

Answers (1)

user3121023
user3121023

Reputation: 8286

strchr could be used to find an = in the literal string.

#include <stdio.h>
#include <string.h>
char* str_get_var(char *string,char delim)
{
    char    *found2 = NULL;

    printf("var string: %s\t",string);

    found2 = strchr ( string, delim);
    if ( NULL != found2) {
        printf ( "string \t\t var found2: %s\n", found2);
    }

    return found2;
}

int main(int argc, char *argv[])
{
    char *message = "ehzg=1";
    char trenner = '=';
    char *gefun = NULL;

    printf ( "Start\n");
    gefun = str_get_var ( message, trenner);
    printf ( "Ende\n");
    if ( NULL != gefun) {
        printf ( "%.*s\n", (int)( gefun - message), message);
        printf ( "%s\n", gefun);
    }
    return(0);
}

Upvotes: 1

Related Questions