简体   繁体   中英

Memory allocation of character array in C++

#include<iostream>
using namespace std;
int main()
{
    cout<<"Enter\n";
    char ch[0];
    cin>>ch;
    cout<<sizeof ch;
    cout<<sizeof &ch;
    cout<<"\n You entered \n"<<ch<<"\n";    
    return 0;
}

I use g++ compiler to compile the C++ program. What is the difference in memory allocation of char ch and char ch[0] . ch can accept one character but ch[0] can accept many character(I put in qqqqqqqq). Why? Also why does sizeof ch return 0 whereas sizeof &ch gives 4, yet ch accepts more than four characters?

Let's take this line by line:

char ch[0];

declares a zero-length array of characters. As mentioned in the comments, C++ standards don't actually allow this, but g++ might.

cin >> ch;

puts whatever's read in into the zero-length array. Since cin doesn't know the length of your array (it decays into a char * when it gets passed to the stream), it writes as much as it feels, which means it can store more than zero characters.

cout << sizeof ch;

outputs the size (ie. total space used in bytes) of the array, which is zero, as mentioned earlier.

cout << sizeof &ch;

outputs the size of the address of the array, which is 4 bytes on your architecture, since it's just a pointer.

cout << "You entered\n" << ch << "\n";

outputs whatever was stored into the array, which isn't well-defined, because, as I mentioned, zero-length arrays are not standard C++. Further, since cout just writes memory until it encounters a null byte ( \\0 ), it writes as much as you stored, since again, cout doesn't care whether you delcared ch with size 0 or size 413 .

What is the difference in memory allocation of char ch and char ch[0].

The difference is in how much the compiler is going to protected you from yourself. An array is just a sequential block of memory, C++ has not array out of bounds exceptions, and doesn't check array bounds before writing. By using

char ch[0];

you have told the C++ compiler you will be responsible for bounds checking. This is a buffer overflow (remember those). When you assign something like 'qqqq' to ch[0] you have overwritten some other piece of memory that belongs to some other variable, function or program. Try running the program below if you need a better understanding.

// Note that I'm setting arr[10], which in Java (or any other modern language) would
// be an array out of bound exception
// I haven't run this program, but you're most likely to get 'a' printed
// to standard out
char arr[10], achar;
arr[10] = 'a';
cout << achar;

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