Segmentation fault (core dumped)

1

There is something wrong with the pointer in this program, whose purpose is to test a function that counts the number of characters in a string. For some reason he can not gain access to the memory to which he points. For this program I created a source and a header:

Main (source) code:

#include <stdio.h>
#include "mystring.h"

 int main() {

 char palavra[20];

 puts("Digite uma paravra qualquer:");
 fgets(palavra, sizeof(palavra), stdin);
 printf("%d", mystrlen(palavra));

 return 0;
}

mystring.h code that contains the mystrlen (header) function:

int mystrlen(char *str) {
    int i = 0; // Contadora
    for (; (*str != '
int main() {

    char str[8] = "Exemplo", *ptr = str;
    int i;

    for (; *ptr != '
#include <stdio.h>
#include "mystring.h"

 int main() {

 char palavra[20];

 puts("Digite uma paravra qualquer:");
 fgets(palavra, sizeof(palavra), stdin);
 printf("%d", mystrlen(palavra));

 return 0;
}
'; ptr++, i++); printf("%d", i); return 0; }
' || *str != '\n'); str++, i++); // Ponteiro percorre a string até o '
int mystrlen(char *str) {
    int i = 0; // Contadora
    for (; (*str != '
int main() {

    char str[8] = "Exemplo", *ptr = str;
    int i;

    for (; *ptr != '%pre%'; ptr++, i++);

    printf("%d", i);

    return 0;
}
' || *str != '\n'); str++, i++); // Ponteiro percorre a string até o '%pre%' ou '\n' return i; }
' ou '\n' return i; }

Below is the code for a similar example that I did. This example, unlike the above program, works here.

%pre%

What can be the problem? Thank you.

    
asked by anonymous 21.03.2016 / 00:34

1 answer

2

You have an error in your loop. You are using OU instead of E:

// versão atual
(*str != '
// versão atual
(*str != '%pre%' || *str != '\n')

// versão correta
(*str != '%pre%' && *str != '\n')
' || *str != '\n') // versão correta (*str != '%pre%' && *str != '\n')

The result of this is that the condition of the loop is always true.

    
21.03.2016 / 02:14