简体   繁体   中英

Execvp not executing args

I can't get execvp to execute the args, this code only works if I set the number of args to 0. I've been trying to change lines here and there for 2 hours and checking other similar questions but nothing is working, maybe someone got an idea?

void executeProgram()
{
    char *argv[20];
    printf("Please enter command or program name:");
    char *commande;
    scanf("%s", commande);
    argv[0] = malloc(100);
    argv[0] = commande;
    int nbArgZ = -1;
    while(nbArgZ < 0){
            printf("Please enter number of arguments:");
            scanf("%d", &nbArgZ);
    }
    int x;
    int y =1;
    for(x = 1; x < nbArgZ+1; x++){
            char *tempo;
            argv[x] = malloc(100);
            printf("Argument %d : ", x);
            scanf("%s", tempo);
            argv[x] = tempo;
            y++;
    }
    argv[y] = NULL;
    int pid = fork();
    if ( pid == 0 ) {
            execvp(argv[0], argv);
    }
    wait(2);
    printf( "End of execution\n");
}

You have multiple problems. Here are a couple of them:

argv[x] = malloc(100);
...
argv[x] = tempo;

First you make argv[x] point to some memory you allocate, then you make argv[x] point to where tempo is pointing, making you lose the original memory.

And about tempo :

char *tempo;
...
scanf("%s", tempo);

You have an uninitialized pointer. Where it is pointing is indeterminate and will seem almost random. Dereferencing this pointer, which happens when you call scanf , leads to undefined behavior .

Both of these issue can be solved by passing argv[x] directly to your scanf call:

scanf("%99s", argv[x]);  // No more than 99 characters (excluding terminator)

And you have the very same problem not once, but twice .

this code

   argv[0] = malloc(100);
    argv[0] = commande;

should set off alarm bells immediately. You assign something toe argv[0], then in the next line set it to something else. That cannot be correct

you need

char commande[100]; // we will assume 100 is enough
scanf("%s", commande);
argv[0] = strdup(commande); // strdup maybe not needed, buts lets be safe

and the same change inside your arg loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM