Scholar
Scholar

Reputation: 293

Why does the following code produce a segmentation fault?

I'm trying to execute a UNIX command via my program that will handle up to 4 arguments, why does this either produce a seg fault or other errors?

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;
}

Upvotes: 0

Views: 129

Answers (3)

codeling
codeling

Reputation: 11398

If you check the man page of execlp, you will notice that the first argument (the second parameter to the method, the arg0 parameter) is mandatory, in addition to any other parameters you might pass to the function via variadic parameters - and it is also mentioned in the text that

The list of arguments must be terminated by a NULL pointer.

The first argument (secondPtr in your case) should be the name of the executable; so you're violating the convention by passing in NULL here (because of the cin >> others have pointed out already).

But in addition, you're also missing at least one more argument at the end which needs to be NULL.

So, a study of man pages is highly recommended!

Upvotes: 1

user823738
user823738

Reputation: 17521

The crash is because your buffer overflows.

Try to use std::cin.getline(buffer, sizeof(buffer)) instead of std::cin >> buffer
Also note that strtok may return NULL, so be sure you handle it.

Upvotes: 2

lolando
lolando

Reputation: 1751

I think you should use

char buffer[255];
cin.getline(buffer, 255);

Otherwise your second, third and fourth pointer will be empty.

Upvotes: 1

Related Questions