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?