I have such a funny problem I thought I’d share with you.
I cornered it down to the most little program I could :
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int cmd_left(char *name)
{
pid_t pid;
int f_d;
if ((pid = fork()) == -1)
{
perror("");
exit(1);
}
f_d = open(name);
printf("%d\n", f_d);
close(f_d);
}
int main(int ac, char **av, char **env)
{
char **dummy_env;
if (ac < 2)
return (0);
dummy_env = malloc(10);
cmd_left(av[1]);
}
Basically, if I remove the malloc, opening works just fine.
You just have to compile and give the program a (valid) file to see the magic.
You need
#include <fcntl.h>to get a declaration foropen()in scope, which would then tell you that you are not calling it with enough arguments:(The optional argument – singular – is the permissions for the file (
mode_t perms) if you haveO_CREATamongst the options in theflagsargument.)The call to
malloc()scribbles over enough stack to remove the zeroes on it initially, which leaves the ‘extra arguments’ toopen()in a state where they are not zero and you run into problems.Undefined behaviour – which you’re invoking – can lead to any weird result.
Make sure you compile with at least ‘
gcc -Wall‘ and I recommend ‘gcc -Wmissing-prototypes -Wstrict-prototypes -Wall -Wextra‘.