简体   繁体   中英

Why does the cin extraction operator cause a segfault?

#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 c is not initialized. You need to allocate memory for the buffer before reading the data into it:

char * c = new char[80];
cin >> c;
cout << c << endl;
delete[] c; // Now you need to delete the memory that you have allocated.

To avoid restricting your input to N characters, use strings. They resize dynamically as you need:

string c;
cin >> c;
cout << c;
// You do not need to manage string's memory - it is done automatically

You've allocated no space at all for the string when you use only char *c; . The variable declaration creates a pointer to char which is uninitialized. Then you use cin to read a string into that space. c could point to anything , and in any case will point to memory that doesn't belong to you.

You'll need to allocate space for the string before you try to fill it from cin .

If you don't want to assume a limit on the string length, you can loop and realloc more space until the input is completely read, but as has been mentioned, if you use std::string instead of C strings, then this will be handled for you.

那是因为你没有为你的字符串分配内存。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM