Thread: Printing string bigger than the maximum size

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193

    Question 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)
    Last edited by thames; 12-13-2012 at 03:44 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Maximum File Size
    By dickyDick in forum C++ Programming
    Replies: 3
    Last Post: 08-04-2005, 12:51 AM
  2. Help!Maximum array size in C?
    By robin in forum C Programming
    Replies: 10
    Last Post: 04-02-2005, 11:57 PM
  3. Maximum size of an array in C
    By mehdi_etebari in forum C Programming
    Replies: 8
    Last Post: 02-01-2005, 09:50 AM
  4. Replies: 28
    Last Post: 12-10-2004, 06:49 AM
  5. Maximum array size?
    By code2big in forum C Programming
    Replies: 2
    Last Post: 05-25-2004, 08:16 AM

Tags for this Thread