0

When running the following code I get the error:

execvp error: Bad address

I am not sure why that is the case but I suspect that cmd[2] should be set to a NULL pointer. I couldn't figure out how to set a NULL pointer for a 2d array of constant size.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {

    char cmd[10][10];
    strcpy(cmd[0], "ls");
    strcpy(cmd[1], "-1");

    int pid = fork();

    // child process
    if (pid == 0){

        execvp(cmd[0], (char *const *) cmd); 
        perror("execvp error"); 

    // parent process
    } else if (pid > 0){
        wait(NULL);

    // fork failure
    } else {
        perror("Child creation unsuccessful");

    }

    return 0;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Joe K
  • 55
  • 4

1 Answers1

3

execvp takes an array of pointers. You give it a 2D array. They are quite different beasts. For starters, the array of pointers given to execvp must be NULL-terminated. With a 2D array it is not possible.

user58697
  • 7,808
  • 1
  • 14
  • 28