0

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.

5
  • 3
    First thing - you do not malloc enough space for the null terminator. Commented Sep 14, 2016 at 17:33
  • 1
    I don't see why using two indices. I think it should be i only. Commented Sep 14, 2016 at 17:35
  • malloc(taille*sizeof(char)); --> malloc(taille+1); and add a nul terminator. Commented Sep 14, 2016 at 17:36
  • Thanks, I tried but the problem is it doesn't print anything. Commented Sep 14, 2016 at 17:44
  • @SNus you may be copying the null terminator into inverse[0] which wouldnt print anything. Commented Sep 14, 2016 at 21:33

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU VERY MUCH, that was it. You're great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.