Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting "segmentation failed" error in strrev function implementation

Tags:

c

void main() { 
    void strrev(char *); 
    char *p="GOOd";
    strrev(p);
    printf("%s",p);
}

void strrev(char *str) { 
    char temp, *end_ptr;
    if( str == NULL || !(*str) ) return;
    end_ptr = str + strlen(str) - 1;

    while( end_ptr > str ) 
    { 
        temp = *str; 
        *str = *end_ptr; 
        *end_ptr = temp; str++; 
        end_ptr--; 
    } 
}

i am getting the error segmentation failed can any one help me out how to sort it out...

like image 889
sarsarahman Avatar asked Dec 09 '11 16:12

sarsarahman


2 Answers

The statement:

char *p = "GOOd";

Defines a string literal "GOOD", pointed by an pointer p.

You are trying to modify this string literal through the strrev function which results in Undefined Behavior(UB) and the crash.

The problem with string literals is they are stored in a read-only(Implementation defined) memory location and user programs are not allowed to change that.If a program attempts to do so it causes an UB.

So instead of using a string literal You should use an array.

You should be using:

char p[] = "GOOd";
like image 55
Alok Save Avatar answered Oct 17 '22 01:10

Alok Save


One problem is that in the following:

char *p = "GOOd";

the compiler is allowed to place the string literal in read-only memory.

Any attempt to modify the string pointed to by p results in undefined behaviour.

Try changing the above line to:

char p[] = "GOOd";

I don't see anything wrong with the strrev() function itself.

like image 24
NPE Avatar answered Oct 17 '22 01:10

NPE