我試圖通過我的程序來執行一個UNIX命令,它將處理多達4個參數,爲什麼這會產生seg故障或其他錯誤?爲什麼下面的代碼會產生分段錯誤?
using namespace std;
int main() {
char buffer[255];
cin >> buffer;
char* firstPtr;
char* secondPtr;
char* thirdPtr;
char* fourthPtr;
firstPtr = strtok(buffer, " ");
secondPtr = strtok(NULL, " ");
thirdPtr = strtok(NULL, " ");
fourthPtr = strtok(NULL, " ");
execlp(firstPtr, secondPtr);
return 0;
}
因爲你調用未定義的行爲? (或者你已經知道)? 'cin >> buffer'正在打破空白,因此在''「'上標記這個是沒有意義的。因此'secondPtr'爲NULL,你快樂地走進UB-land。 – WhozCraig
「或其他錯誤?」哪些其他錯誤? – codeling
當我exec的LS我得到的錯誤是NULL傳遞做argv [0] – Scholar