Reputation: 38
I have a function that looks like this:
int lexWhitespace(TokenizerOutput* input) {
printf("he");
if (!(14 > input->toStillParse[0] > 8) && !(input->toStillParse[0] == 32)) {
// checks if the first character in the toStillParse section of input is whitespace.
return -1;
} else {input->tokenizerOutput[0] = input->toStillParse[0];}
for (int i = 1; ; i++) {
if ((14 > input->toStillParse[0] > 8) || (input->toStillParse[0] == 32)) {
// checks if the first character in the toStillParse section of input is whitespace.
input->tokenizerOutput[i] = input->toStillParse[i];
} else {return 0;}
}
}
that takes in this struct:
struct TokenizerOutput {
const char* toStillParse; // holds the text that still needs to be parsed.
char* tokenizerOutput; // holds the text that was just output by tokenizer function.
};
typedef struct TokenizerOutput TokenizerOutput;
When I try to call it in the main function like this:
int main(void) {
printf("hello\n");
TokenizerOutput j = {" k", " "};
printf("%s\n", (&j)->toStillParse);
lexWhitespace(&j);
return 0;
}
I get a segfault. The segfault is occuring before the function lexWhitespace even runs anything because it does not print "he". I have no idea why this is happening. Any help would be greatly appreciated. I am using gcc 9.3.0.
Upvotes: 0
Views: 42
Reputation: 213358
There are some errors in this code.
First, this condition:
14 > input->toStillParse[0] > 8
This is probably unintentional. It is probably meant to be written as:
14 > input->toStillParse[0] && input->toStillParse[0] > 8
Second, this loop may never terminate:
for (int i = 1; ; i++) {
if ((14 > input->toStillParse[0] > 8) || (input->toStillParse[0] == 32)) {
// checks if the first character in the toStillParse section of input is whitespace.
input->tokenizerOutput[i] = input->toStillParse[i];
} else {return 0;}
}
Note that the character being compared, toStillParse[0]
, is the same character each loop iteration. So this loop will either exit immediately, or it will loop forever (and probably crash / segfault). It looks like the [0]
should be [i]
. Also note that the condition is probably written wrong.
In C, x > y > z
is not the same thing as x > y && y > z
. Whenever you see x > y > z
, it is probably wrong (unless you're looking at IOCCC entries or something).
Upvotes: 1