1
There is something wrong with the pointer in this program, which aims to test a function that counts the number of characters in a string. For some reason he can’t access the memory he points to. For this program I created a source and header:
Main code(source):
#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 containing the function mystrlen
(header):
int mystrlen(char *str) {
int i = 0; // Contadora
for (; (*str != '\0' || *str != '\n'); str++, i++);
// Ponteiro percorre a string até o '\0' ou '\n'
return i;
}
Below is the code of a similar example I did. This example, unlike the above program, works here.
int main() {
char str[8] = "Exemplo", *ptr = str;
int i;
for (; *ptr != '\0'; ptr++, i++);
printf("%d", i);
return 0;
}
What could be the problem? Thank you.
To debug segmentation fault I strongly recommend that you use a debugger that allows you to run the program one step at a time, such as ddd or gdb. These debuggers will also inform you right the line number with the segmentation failure, the status of the call stack and the value of your variables.
– hugomg
In the second example the variable
i
has not been initialized. This may be a source of unpredictable behavior. btw, I’m not a fan of this compact style of writing C, a-la K&R. I think things get clearer with a command per line.– hugomg
Well, the curious thing is that the second example works...
– Jefferson Carvalho
I don’t understand... what is the program that gives dick? Please include the entire program that you are running, without breaking it in parts.
– hugomg
I edited the question to try to make it clearer
– Jefferson Carvalho
in English: this line:
(*str != '\0' || *str != '\n');
has a problem. with the||
one or the other of the Expressions will Always betrue
the line should be:(*str != '\0' && *str != '\n');
– user3629249
in English: in the Second posted code, the variable
i
is not initialized Suggest replace:int i;
withint i=0;
– user3629249