exec bad adress, NULL addet

I try to use execvp and it worked fine, but now I chanced the way to declare the arguments and now I get "bad address" as error. I red a lot of same problems and the problem was the NULL as last argument.

I tried a lot of ways to append the NUll on the end but it doesnt work.

char *args4exec[5];

        case 1:
          printf("case 1 arg\n" );
          args4exec[2] = NULL;
        case 2:
          printf("case 2 args\n" );
          strcpy(&args4exec[3], NULL);

    if (execvp( args4exec[0], args4exec) == -1 )
      perror("exec failed");

strcpy and normal defintion doesnt work, Can anyone help me? The code I posted doesnt work but it should show the ways I tried to add the NULL.


1 Answers exec bad adress, NULL addet

before copy your command or another strings to args4exec you should allocate memory for it:

char *args4exec[5];
char *command = "Hello";
args4exec[0] = malloc(sizeof(char) * strlen(command));

Also here is error in your strcpy() compiler should warn about it. Should be like this:

strcpy(args4exec[0], command);

if you use gcc compile with -Wall -Wextra -Werror.

And you should check your args[i - 2] and other parameters to be sure that they store correct values and not out of bounds.

5 months ago