Problems with using execvp on a constructed string

微笑、不失礼 提交于 2019-12-02 04:58:58

问题


I'm trying to write a shell, and part of its construction is executing code from a user-inputted string (buffer). However, when I attempt to execvp the string with additional inputs (ae. echo a), it always screws the pooch and returns -1. I'm at a loss as to why. Here's the relevant pieces:

char * buffer = calloc(100, sizeof(char));
...
fgets(buffer, 100, stdin);
buffer[strlen(buffer) - 1] = 0; // necessary because of a newline inserted by fgets
...
cmd = strsep(&buffer, " ");
char * str = malloc(50 * sizeof(char));
strcat(str, "./");
strcat(str, cmd);
strcat(str, ".out");
...
i = execvp(str, (char * *) buffer);

回答1:


The argument buffer is wrong. The second argument of execvp is an array of pointers. With this cast, you are hidding a compiler warning, but it does not work.




回答2:


I can see a couple of potential problems here.

First, you're allocating space with malloc (meaning the contents aren't initialized), but immediately using strcat to write to it. Unless (by whatever change) the first character is a '\0', that's going leave you with a string starting with garbage, followed by data you're trying to put there. It would also (very easily) lead to writing past the end of the buffer, giving undefined behavior.

If it were up to me, I think I'd use sprintf instead of strcat. At least what you've shown would work out to: sprintf(str, "./%43s.out", cmd);




回答3:


Two problems:

  1. You are passing an uninitialized string to the first strcat.
  2. execvp expects an array of strings, not a single string with null-separated fields.


来源:https://stackoverflow.com/questions/13779872/problems-with-using-execvp-on-a-constructed-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!