I am working on creating my own UNIX shell and some times when I run 'ls' command it gives an error bad address

I am wondering if there is an error with execvp calling ls that can cause it to fail occassionally and then work properly other times.

void lookInsideCurrentDirectory(char **parsed){
    char* line = NULL;
    pid_t pid = fork();

    if(pid == -1){
    else if(pid == 0){
        if(execvp(parsed[0], parsed) == -1){
            perror("Error: ");


answered 1 week ago Lie Ryan #1

According to https://www.gnu.org/software/libc/manual/html_node/Error-Codes.html:

Macro: int EFAULT

    “Bad address.” An invalid pointer was detected.

If you receive this error from execvp, that means that some of the pointer in parsed was invalid. You should look into the rest of the program and make sure any strings in the parsed array are not free()-ed until the execvp calls are completed.

Another very common mistake is that since you're not passing the length of the argument array to execvp, the argv argument must be a NULL-terminated array, so that execvp knows when to stop reading arguments. That means that if you're receiving command that looks like so: ls -lah /bin then your argv array should be one larger and end it with a NULL pointer:

char** argv = {"ls", "-lah", "/bin", NULL};

If you don't end the argv with a NULL pointer, execvp will try to dereference whatever comes next in the memory as an pointer address, and unless it happens to contain NULL bytes, then the derefence likely will fail or may dereference to unexpected things.

comments powered by Disqus