As a hacker-in-training, I decided to go about making my own string_reverse function that takes a string, allocates memory for a new string, and returns a pointer to a new string, but I'm not getting what I desire, as this returns a segmentation fault.
#include <stdio.h>
#include <stdlib.h>
char* string_reverse(char* string);
char* string_reverse(char* string) {
int len = 0;
for (int i = 0; *(string + i) != '\0'; ++i)
len++;
char* result = (char*)malloc(len * sizeof(char));
if (result == NULL){
puts("Pointer failure");
exit(EXIT_FAILURE);
}
for (int i = 0; *(string + i) != '\0'; ++i)
*(result + (len - i)) = *(string + i);
return *result;
}
int main() {
char* str= "Ni Hao!";
char* result = string_reverse(str);
printf("%s\n", result);
free(result);
return 0;
}
In return, I get this debugging message:
Starting program: /home/tmo/string_reverse
Program received signal SIGSEGV, Segmentation fault.
0xb7e5b3b3 in strlen () from /lib/i686/cmov/libc.so.6
How should I interpret this result?