Question

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

Was it helpful?

Solution

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;
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top