简体   繁体   中英

Default dynamic memory size

I have the following code:

#include <iostream>`

using namespace std;
int main() {
    char* data = new char;
    cin >> data;
    cout << data << endl;
    return 1;
}

When I type in a char* of 26 ones as a string literal, it compiles and prints it. But when I do 27 ones as data, it aborts. I want to know why.

Why is it 27?

Does it have a special meaning to it?

You're only allocating one character's worth of space. So, reading in any data more than that is overwriting memory you don't own, so that's undefined behavior. Which is what you're seeing in the result.

Your dynamically allocating one byte of storage. To allocate multiples, do this:

char* data = new char[how_many_bytes];

When you use a string literal, that much stack space is allocated automatically. When you allocate dynamically, you have to get the number of bytes right or you will get a segfault.

This is just Undefined Behavior , aka "UB". The program can do anything or nothing. Any effect you see is non-reproducable.

Why is it UB?

Because you allocate space for a single char value, and you treat that as a zero-terminated string . Since the zero takes up one char value there is no (guaranteed) space for real data. However, since C++ implementations generally do not add inefficient checking of things, you can get away with storing data in parts of memory that you don't own – until it crashes or produces invalid results or has other ungood effect, because of the UB.

To do this correctly, use std::string instead of char* , and don't new or delete (a std::string does that automatically for you).

Then use std::getline to read one line of input into the string.

You'd have to look into specific details under the hood of your C++ implementation. Probably the implementation of malloc , and so on. Your code writes past the end of your buffer, which is UB according to the C++ standard. To get any idea at all of why it behaves as it does, you'd need to know what is supposed to be stored in the 27 or 28 bytes you overwrote, that you shouldn't have done.

Most likely, 27 ones just so happens to be the point at which you started damaging the data structures used by the memory allocator to track allocated and free blocks. But with UB you might find that the behavior isn't as consistent as it first appears. As a C++ programmer you aren't really "entitled" to know about such details, because if you knew about them then you might start relying on them, and then they might change without notice.

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