user905292
user905292

Reputation: 21

c language strchr segmentation fault character replace

I need to replace every occurence of '&' to ',' in a C string.

I did this and it works

Code 1:

char *val, *querydup;
.
.
.
val=strchr(querydup,'&');
while(val != NULL) {
*val=',';
val=strchr(querydup,'&');
}

In order to be "elegant" I tried the following, but it leads to seg fault, to the point where even my pointer cursor gets corrupted!. weird, I'm running linux inside a vmware vm.

Code 2:

while(val=strchr(querydup,'&') != NULL) {
*val=',';
}

So what could be wrong?..

Do you consider code 1 to be "elegant"?...

Regards.

Upvotes: 1

Views: 2042

Answers (4)

emboss
emboss

Reputation: 39650

It's the operator precedence, try

while((val=strchr(querydup,'&')) != NULL) {
    *val=',';
}

Upvotes: 4

Paul
Paul

Reputation: 141857

You are assigning val a boolean value. Your code is equivalent to:

while(val = (strchr(querydup,'&') != NULL))

Change it to:

while((val = strchr(querydup,'&')) != NULL)

Upvotes: 1

pmg
pmg

Reputation: 108978

Your main issue has been answered by emboss.

I'm answering the "elegance" part :)

You're checking the same characters over and over again.

Suppose querydup has "&&&&&&&&&&". After the first few changes it has ",,,,,,&&&&" and yet you still check from the beginning anyway.

Try re-using val for "elegance" :)

val = strchr(val, '&');

Upvotes: 6

Doug Kress
Doug Kress

Reputation: 3537

Perhaps a simpler solution would be to actually do it manually:

char *ptr = querydup;
while (*ptr) {
    if (*ptr == '&') {
        *ptr = ',';
    }
    ptr++;
}

It's more lines of code, but it only goes through the string once, where the repeated executions of strchr() will go through the string multiple times.

Upvotes: 3

Related Questions