Helper
Helper

Reputation: 19

Whats the reason for segmentation fault

The code runs and asks for the command. I am able to put in input but after I hit enter I get a segmentation fault. Struggling to understand what is the reason for this. I pretty sure it has something to do with the cin as thats were it crashes but cant figure it out.

int main(){
    while(1){
            int status;
            char work[100];
            char** arr = new char*[100];

            cout << "Enter a command:" << endl;
            cin >> arr[0];

            if(fork() != 0){
                    waitpid(-1, &status, 0);
            }else{
                    execlp(arr[0], "ls", NULL);
            }
    }

Upvotes: 1

Views: 124

Answers (1)

Richard Day
Richard Day

Reputation: 49

char** arr = new char*[100];

This is an array of POINTERS, uninitialized pointers to be precise. They could point anywhere...

Try this instead:

char* arr = new char[100]; // your going to leak this btw

Now you have a block of 100 chars, still uninitialized!

Your cin isn't safe, you need to be using getline or something similar. Ever heard of buffer overflow?

Upvotes: 1

Related Questions