S Nus S Nus - 2 months ago 10
C Question

What is wrong with my program reversing strings in C?

I want to create a function to reverse a string in C. I found a couple pre-made on the internet but I wish to create mine. Here is the code:

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


char* inverseCarac(char* chaine){
if(chaine==0||*chaine==0) return NULL;

int j, i;
int taille=strlen(chaine);
char* inverse=malloc(taille*sizeof(char));

for(j=taille-1, i=0; j>0; j--, i++){
*(inverse+i)=*(chaine-j);
}

return inverse;

}

int main(void){
char* test="bonjour";
char* inv=inverseCarac(test);
printf("%s", inv);
return 0;
}


I can't figure out why I get a segmentation fault.

Answer

There were several errors in your code, the most significant being the offset from chaine in the wrong direction. Also, lack of space for a string terminator, and j ending prematurely.

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

char* inverseCarac(char* chaine){
    if(chaine==0||*chaine==0) return NULL;  

    int j, i;
    int taille=strlen(chaine); 
    char* inverse=malloc(taille+1);             // add 1 for terminator

    for(j=taille-1, i=0; j>=0; j--, i++){       // change j>0 to j >= 0
        *(inverse+i)=*(chaine+j);               // change -j to +j
    }
    inverse[taille] = '\0';                     // write terminator
    return inverse;
}

int main(void){
    char* test="bonjour";
    char* inv=inverseCarac(test);
    printf("%s\n", inv);
    return 0;
}

Program output

ruojnob