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;
}
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.