(Error of Segmentation fault)

Asked

Viewed 81 times

0

People don’t know where the bug is. Every time I compile it accuses error of Segmentation fault (core dumped), 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;
}
  • Possible duplicate of Simple Teaching of Pointers

  • In strlen, you did not define the initial value of i, so he’s memory junk

  • Another alternative would be that the sentence size is too large

  • 1

    Caraca hadn’t even noticed , @Jeffersonquesado pela ajuda.

  • @Patrickcardoso I transformed in response to stay stored the correct history

  • @Patrickcardoso, if the answer (born of the comment) solves your problem in the correct way, please mark as the answer accepted.

Show 1 more comment

2 answers

2

It was a little careless.

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

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

Like i not initialized, it starts with memory junk

0

It seems to me that you do not know the "string. h" library, because it is trying to recreate ready-made functions such as "strlen()" and "strrev()". It is mt 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;
}
  • 1

    Your answer does not focus on the error quoted does not ask. Remember that the questioner may be trying to recreate the functions in string.h to learn and practice.

  • Yes I know, but I’m recreating these functions to practice, you know?

  • @Isac Exactly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.