systemasis systemasis - 1 year ago 48
C Question

execle returns a bad adress when called in a loop

For a project, I have to be able to launch multiple instances of a couple of programs to run simultaneously. To do so, I use

to be able to pass some parameters if needed. Here's (roughly) my code :

char **my_env;

if(argc == 10){
my_env[0] = malloc(20+sizeof(argv[9]));
my_env[1] = NULL;
snprintf(my_env[0], 20+sizeof(*argv[9]), "PREFIXE=%s", argv[9]);
my_env[0] = NULL;

for(i=1; i <= n; i++){
if((pid=fork()) == 0){
execle(first_program, first_program, some_args, ..., (char *) 0, my_env);
perror("Error at first_program's launch");
if((pid = fork()) == 0){
execl(second_program, second_program, some_args, ..., (char *) NULL, my_env);
perror("Error at second_program's launch");

execle(third_program, third_program, some_args, ..., (char *) NULL, my_env);
perror("Error at third_program's launch");

My problem is when
is greater than 1, the execle for second_program and third_program returns a bad adress weither
or not.

When I replaced them by
, everything works fine.

Answer Source

You never initialize memory for my_env. You tell the compiler

char **my_env;

that means my_env is a pointer * to an array of char * pointers. Okay... but directly after that declaration, my_env has a random value, so it is a pointer to random memory. Where is that array it points to? You have not yet created such an array, you just declared a pointer to one.

You then just use my_env, either like this

my_env[0] = ...;

This means "write the value ... to the first entry of the array my_env points to"... again, what array? Your my_env doesn't point to any array!

Either you must provide static memory for my_env:

char * my_env[2] = { NULL, NULL };

or dynamic:

char ** my_env = calloc(sizeof(char *), 2);
// ... and when you are done with it ...