1

segmentation fault after running the following code:

int main(){
    const char *string = "This is not reverse";
    char *reverse;
    char temp;
    int length, i = 0;
    length = strlen(string);
    strcpy(reverse, string);

    while(i < (length/2)){
       temp = *(reverse+i); // this is the reason for segmentation fault..but why? 
       i++;
    }

}

could someone please explain the reason for the same

codey modey
  • 983
  • 2
  • 10
  • 23

2 Answers2

4

You need to allocate space for reverse. For example

char *reverse = malloc(strlen(string) + 1);

By the way, the rest of the code seems to have an algorithmic bug. I think what you wanted to do was something like:

#include <string.h>
#include <malloc.h>

int main(){
  const char *string = "This is not reverse";
  int length = strlen(string);
  char *reverse = malloc(length + 1);

  int i = 0;
  while(i < length){
    *(reverse + i) = *(string + length - i - 1);
    i++;
  }

  printf("%s\n", reverse);
  return 0;
}
Eamonn O'Brien-Strain
  • 3,352
  • 1
  • 23
  • 33
-1

instead of strcpy(reverse, string); use reverse = string, Because you don't need to allocate space for reverse, Just point reverse to string i.e reverse = string

twid
  • 6,368
  • 4
  • 32
  • 50
  • if I point it to the address of a const char i won't be able to edit it. does that makes sense? – codey modey Nov 10 '13 at 06:47
  • @user2901020: you're right that you must copy the string literal to an array that can be modified. – Jonathan Leffler Nov 10 '13 at 06:47
  • user2901020: Has valid point, in that case either you define `const` pointer, Because looking at your code it seems you are not modifying string. Or you have to copy string. If you think it's i am happy to delete my answer, as it might be misleading – twid Nov 10 '13 at 06:55
  • hmm..but, why would you like to delete your answer..many people might think like that..even my question is not an awesome question..it is all about learning either from right or wrong things..in fact, we learn more from the wrong things..cheers! – codey modey Nov 10 '13 at 07:09