Reputation: 145
I'm trying to write my own code to walk the PATH to find an executable as a learning exercise in C programming. (after sucess I might replace it with someone else's code, but for now I want to understand my mistakes).
The following section of code is not jumping to the else statement I expect ...
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define EXECUTABLE S_IXOTH /* executable by others */
#define MAX_PATH_LEN 1024
void message (const char *msg)
{
fprintf(stdout, "INFO: %s\n", *msg);
}
int main (int argc, char *argv[], char *envp[])
{
char *editor;
struct stat editor_stat;
char full_path[MAX_PATH_LEN];
int found_path;
memset(full_path,0,MAX_PATH_LEN);
strcpy(full_path,"/bin/ed");
found_path=stat(full_path,&editor_stat);
if (found_path!=0) {
editor=NULL;
message("The EDITOR specified is not found in the PATH. Using default editor");
} else {
if (editor_stat.st_mode&EXECUTABLE==0) {
editor=NULL;
message("The EDITOR specified must have world execute permission. using default editoe");
} else {
editor=full_path;
}
}
}
When I track it with gdb I see it jumps to the 2nd else instead of the first one, and doesn't execute the check for executable ...
(gdb) file /tmp/sample2
Reading symbols from /tmp/sample2...done.
(gdb) b 28
Breakpoint 1 at 0x400688: file /home/ken/c/shorter_sample.c, line 28.
(gdb) r
Starting program: /tmp/sample2
Breakpoint 1, main (argc=1, argv=0x7fffffffe1f8, envp=0x7fffffffe208)
at /home/ken/c/shorter_sample.c:28
28 if (found_path!=0) {
Missing separate debuginfos, use: debuginfo-install glibc-2.13-2.x86_64
(gdb) p found_path
$1 = 0
(gdb) s
36 editor=full_path;
(gdb)
it should jump to line 32 not 36.
I've tried searcing here for C ambiguity and I've read the sections from "C" by Kernighan & Ritchie that are referenced in the index under C ambiguity, and stuck as many curly braces as I can in the code but the compiler isn't doing what I intend.
FYI, I'm using gcc-4.5.1-4.fc14.x86_64 with kernel 2.6.35.14-106.fc14.x86_64 on Fedora 14.
Upvotes: 2
Views: 193
Reputation: 54554
&
has a lower operator precedence than ==
; that means the second if
statement is equivalent to:
if (editor_stat.st_mode&(EXECUTABLE==0))
I'm going to go out on a limb and say EXECUTABLE
is not 0
, which makes the if
equivalent to:
if (editor_stat.st_mode & 0)
or
if (0)
The second if
statement should be:
if ((editor_stat.st_mode&EXECUTABLE)==0)
Upvotes: 7