Apr 11, 2012 at 8:56pm UTC
I'm building a shell (as an exercise for school), and I receive a segmentation fault when I use fgets as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main() {
char userCommand[MAXLENGTH];
list<varType> variables;
stack<string> dirStack;
vector<string> command;
list<jobType> jobs;
while (1) {
userCommand[0] = '\n' ;
while (userCommand[0] == '\n' ) {
cout << "smash > " ;
userCommand[0] = '\n' ;
fgets(userCommand, MAXLENGTH, stdin);
}
...
}
What am I doing wrong?
Thanks.
Last edited on Apr 11, 2012 at 9:00pm UTC
Apr 12, 2012 at 2:37am UTC
¿why are you using fgets() instead of std::getline (or std::istream::getline() ) ?
I don't see anything wrong with your code, but it looks a little obfuscated.
¿what is the value of MAXLENGTH ?
Apr 12, 2012 at 7:22am UTC
it works well in my test.
[root@localhost cpp]# cat fgets.cpp
#include<iostream>
#define MAXLENGTH 500
int main() {
char userCommand[MAXLENGTH];
userCommand[0] = '\n';
if (userCommand[0] == '\n') {
std::cout << "smash > ";
userCommand[0] = '\n';
fgets(userCommand, MAXLENGTH, stdin);
std::cout<<userCommand<<std::endl;
}
}
[root@localhost cpp]# gcc fgets.cpp -o fgets -lstdc++
[root@localhost cpp]# ./fgets
smash > ebay.com
ebay.com
Apr 12, 2012 at 1:54pm UTC
fgets is faster than std::getline :P
Apr 12, 2012 at 1:59pm UTC
Thanks for the help, but I found the mistake in a location further in the code.
I didn't think it could be there because I tried to figure out where the mistake is by printing things, and fgets was the only command it couldn't pass. I don't really understand how it happened.