char *find_path(char **envp) {
if (envp = NULL || *envp = NULL)
return 0;
while (ft_strncmp("PATH=", *envp, 5))
envp ;
return (*envp 5);
}
I tried envp
to be zero, also tried comparing string of PATH
not found in envp
(environmental variable) using strcmp
but it causes the segmentation fault.
I want to test if we unset the PATH
, I want to return the function as normal and not cause a segmentation fault.
CodePudding user response:
Please format your code before posting; it's difficult to read when it's weirdly indented like that.
To check for equality in C, you must use ==
, not =
. =
will set envp
to NULL
and return its new value. Since this value is 0, the if
clause will be evaluated to false
and return 0
won't execute. Also, you should have tested what happens if envp
isn't 0 before assuming that's the problem. Your code fragment causes a segmentation fault no matter what value envp
is entering the function, since it's changed to NULL
anyways.
char *find_path(char **envp)
{
if (envp == NULL)
return 0;
if (*envp == NULL)
return 0;
while(ft_strncmp("PATH=", *envp, 5))
envp ;
return (*envp 5);
}
CodePudding user response:
Aside from the typo in the first if
statement (both =
should be ==
), which is probably a mistake copying your code into the question, it should be clear that if
while(ft_strncmp("PATH=", *envp, 5)) envp ;
doesn't find PATH=
in the environment, it will reach the NULL terminator at the end of the envp
array, which it will then dereference (and blow up).
CodePudding user response:
There are multiple problems:
bad indentation: it made the code hard to read for both you and the next programmer. Your school might enforce local coding style rules by giving a fail mark (0) for badly indented code.
the tests
envp = NULL
and*envp = NULL
are incorrect: the=
operator setsenvp
toNULL
and this evaluated to false, then||
attempts to set*envp
toNULL
, causing the segmentation fault as*envp
is now a null pointer. You should use==
instead of=
The
while
loop does not have a proper ending condition: ifenvp
reaches the end of theenviron
array,*envp
will be a null pointer, potentially causingft_strncmp
to crash (depending if it tests for null pointers or not). You should iterate while the*envp
is non null and return*envp 5
if the comparison returns0
. This removes the need for the second initial test.
Here is a modified version:
char *find_path(char **envp) {
if (envp) {
while (*envp) {
if (ft_strncmp("PATH=", *envp, 5) == 0)
return *envp 5;
envp ;
}
}
// no environment or PATH not found: return a null pointer
return 0;
}