Printing string bigger than the maximum size
Good evening. Why was possible to print a string with 14 bytes when I just allocated 6 bytes for it ?
Code:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXSIZE = 20;
int main(void)
{
char name[MAXSIZE];
char lastName[MAXSIZE];
cout << "Enter your first name: ";
cin.get(name, MAXSIZE).get();
cout << "Enter your last name: ";
cin.get(lastName, MAXSIZE).get();
// lastName, name\0
char *fullName = new char[strlen(name)];
strcpy(fullName, lastName);
strcat(fullName, ", ");
strcat(fullName, name);
cout << "Here's the information in a single string: " << fullName << endl;
delete fullName;
return 0;
}
Code:
thames@semaht ~/C++/Strings $ g++ -g -Wall personinfo2.cpp -o personinfo2
thames@semaht ~/C++/Strings $ gdb -q personinfo2
Lendo símbolos de /home/thames/C++/Strings/personinfo2...concluído.
(gdb) break 26
Ponto de parada 1 at 0x400cd2: file personinfo2.cpp, line 26.
(gdb) r
Starting program: /home/thames/C++/Strings/personinfo2
Enter your first name: thames
Enter your last name: thames
Breakpoint 1, main () at personinfo2.cpp:26
26 cout << "Here's the information in a single string: " << fullName << endl;
(gdb) print fullName
$1 = 0x603010 "thames, thames"
(gdb) print strlen(fullName)
$2 = 14
(gdb) print strlen(name)
$3 = 6
(gdb) c
Continuando.
Here's the information in a single string: thames, thames
[Inferior 1 (process 2738) exited normally]
(gdb)