(Segment fault fault) Make a program that receives two distinct sentences and prints inverted

0

I do not know where the error is. Every time I compile accuse segmentation fault (core dumped) error, can anyone help me? The code is here:

#include <stdio.h>

int strlen(char *s);
char *strrev(char *s);

int main() {
char frase1[30+1];
char frase2[30+1];

printf("Digite uma frase: ");
gets(frase1);
printf("Digite outra frase: ");
gets(frase2);
printf("Frase 1 = %s\n", strrev(frase1));
printf("Frase 2 = %s\n", strrev(frase2));

return 0;
}

int strlen(char *s) {
int i;
while(s[i]) {
    i++;
}
return i;
}

char *strrev(char *s) {
int i, len;
char aux;
for(i=0,len=strlen(s)-1; i<len; i++, len--) {
    aux = s[i];
    s[i] = s[len];
    s[len] = aux;
}
return s;
}
    
asked by anonymous 21.09.2017 / 00:11

2 answers

2

It was a little oversight.

In strlen , the value of i is not initialized. The following code fixes:

int strlen(char *s) {
  int i = 0;
  while(s[i]) {
    i++;
  }
  return i;
}

As i has not been initialized, it starts with memory garbage

    
21.09.2017 / 00:49
0

It seems to me that you do not know the library "string.h", because it is trying to recreate already ready functions, like "strlen ()" and "strrev ()". It's simple to solve your problem, just use the library "string.h" and use the functions.

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

int main() {
    char frase[31];
    printf("Digite uma frase: ");
    gets(frase);
    printf("Frase invertida = %s\n", strrev(frase));
    return 0;
}
    
21.09.2017 / 00:58