Search code examples
csegmentation-faultreversec-stringsstring-literals

Segmentation Fault accessing string in another function


It can be a rookie mistake however I am not able to point out reason for this Segmentation Fault. Below is the code :

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

void revString(char *str){

    int n = strlen(str);
    char temp;

    for( int i = 0 ; i < n/2 ; i ++ ){
        // swap two chars. 

        temp = str[i];
        str[i] = str[n-i-1];
        str[n-i-1] = temp ; 
    }
}


int main()
{
    char *arr[2] = {"one","two"};
    printf("%s \n",arr[0]);  
    revString(arr[0]);
    printf("%s \n",arr[0]);
    return 0;
}

After tracking the bug using GDB, it is happening at step str[i] = str[n-i-1]. This is because of accessing str[0] and updating its value. Why is it illegal operation?


Solution

  • From the C Standard (6.4.5 String literals)

    7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    So change the array of pointers to first characters of string literals

    char *arr[2] = {"one","two"};
    

    to a two-dimensional character array like for example

    char arr[2][4] = {"one","two"};
    

    Pay attention to that it is better to define the function like

    char * revString( char *str )
    {
        for ( size_t i = 0, n = strlen( str ) ; i < n/2 ; i++ )
        {
            // swap two chars. 
            char temp = str[i];
            str[i] = str[n-i-1];
            str[n-i-1] = temp ; 
        }
    
        return str;
    }