Mathieu_Du
Mathieu_Du

Reputation: 827

Magic in C with malloc, fork and open

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.

Upvotes: 0

Views: 315

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 754700

You need #include <fcntl.h> to get a declaration for open() in scope, which would then tell you that you are not calling it with enough arguments:

int open(const char *filename, int flags, ...);

(The optional argument - singular - is the permissions for the file (mode_t perms) if you have O_CREAT amongst the options in the flags argument.)

The call to malloc() scribbles over enough stack to remove the zeroes on it initially, which leaves the 'extra arguments' to open() 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'.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96286

The header file for open is missing and open expects at least a second parameter.

If you fix that it should be OK.

Upvotes: 1

ninjalj
ninjalj

Reputation: 43718

open(2) takes at least two parameters. Since you are passing it only one argument, you are invoking Undefined Behavior. In this case, open() is just using some garbage as second argument.

Upvotes: 4

Related Questions