#include <iostream>
using namespace std;
int main() {
char * c;
cin >> c;
return 0;
}
I’m trying to get a C string line from the user whose length is not known. I know that if I declared c as char c[80] instead of char * c then it wouldn’t cause a segfault.
However what if I didn’t want to restrict the user to 80 - 1 characters? I could use a really big number but that would just waste space.
I would also really like to know why the above program causes a segfault. From what I understand the cin extraction operator (>>) knows to NULL terminate a C string. What exactly is causing the problem?
The program segfaults because the pointer
cis not initialized. You need to allocate memory for the buffer before reading the data into it:To avoid restricting your input to
Ncharacters, use strings. They resize dynamically as you need: