3
I have the following code:
int i=0;
variable a;
a.type = CHAR;
a.name = malloc(sizeof(char)+1);
while(*l->str++ != ' ');
while(*l->str != ';' || *l->str != '='){
a.name = realloc(a.name, ((!i)?1:i)*sizeof(char)+1);
a.name[i] = *l->str;
i++;
*l->str++;
}
a.name[i] = '\0';
printf("%s\n", a.name);
But he gives segment fault
.
When I withdraw the *l->str != '='
or the *l->str != ';'
of the condition of while
it works normally. I wonder why it gives segment fault
and if there is any way without if
to solve.
What is
l->str
? Where is the statement of this?– Havenard
It’s been a while since I’ve programmed in C, what’s the precedence of the operators
||
and!=
? Could the compiler be interpreting this as*l->str != (';' || *l->str) != '='
?– mgibsonbr
I don’t think so, I’m pretty sure that’s not the problem.
– Havenard
The condition
*l->str != ';' || *l->str != '='
will always be true. The only way she can be false is if*l->str
for;
and=
at the same time. Obviously, this will never happen. The same variable cannot have two different values.– Havenard
@Havenard I believe you are right about precedence. The problem is right in the condition.
– mgibsonbr