Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C++ char array seem to be able to hold more than its size?

Tags:

c++

char

g++

#include <iostream>
using namespace std;

typedef struct
{
    char streetName[5];

} RECORD;

int main()
{
    RECORD r;
    cin >> r.streetName;
    cout << r.streetName << endl;

}

When I run this program, if I enter in more than 5 characters, the output will show the whole string I entered. It does not truncate at 5 characters. Why is that?

How can I get this to work correctly?

like image 844
neuromancer Avatar asked May 22 '10 18:05

neuromancer


People also ask

Why is the size of character arrays declared one more than the largest string they can hold?

The maximum index value of most arrays, therefore, is one less than its numerical value. It's same with a string, but since it has an extra character at the end, it gets incremented by one. So, the string length is the same as the number of characters in it.

What is the maximum size of character array in C?

The maximum allowable array size is 65,536 bytes (64K). Reduce the array size to 65,536 bytes or less. The size is calculated as (number of elements) * (size of each element in bytes).

How do you change the size of a char array?

Arrays cannot be resized. Blocks of memory can. You can declare char (*my_test)[10]; to create a pointer to an array of 10-chars and then allocate/reallocate the number of 10-char arrays in that block. Or, you can decalre char **my_test; and allocate and reallocate each individual block each pointer points to.

How can I increase my character size?

To change your display in Windows, select Start > Settings > Accessibility > Text size. To make only the text on your screen larger, adjust the slider next to Text size. To make everything larger, including images and apps, select Display , and then choose an option from the drop-down menu next to Scale.


1 Answers

You are overflowing the buffer. Put another char array after streetName and you will likely find that it gets the rest of the characters. Right now you are just corrupting some memory on your stack.

like image 64
twk Avatar answered Oct 13 '22 11:10

twk