'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);
}
}
Solution 1:[1]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Coding Mason |
