1

I am just starting C++ and I can't understand how my code works:

Ok I allocate memory, but at the time of the allocation nobody knows the size of the memory to be allocated. But still the code works. How much memory is allocated? How the compiler knows how much memory I will need?

EDIT:

Sorry if my question was not clear. Let me please try clarify it. So I dynamically allocate some memory in the heap by using my pointer. But since there is no text in the sting variable, in my opinion it is quite difficult to know how much text (bytes) I will enter via getline.

I tried asking the size of two different text literals, and yes they are different in size.

sizeof("") // is 1 (because of the ending 0 maybe?)
sizeof("sometext") // is 9

But for the string: the sizeof gives me 4 both times. It's clear that the sizeof() gives me the length of the pointer pointing to the string.

How can I allocate memory? If I allocate memory for a new string, only allocates to a pointer pointing to the memory address of the first character in the string? Obviously the characters I enter must be stored somewhere. And I first allocate the memory, and then I load some text into it.

Edit 2: make the edited code to look code, not plain text.

//Edit:    
string a,b = "sometext"; 
    cout << sizeof(a) << endl; //4
    cout << sizeof(b); //4

//--------------------------------------------------------

#include <iostream>
#include <string>
#include <exception>



using namespace std;

int main()
{
    //Defining struct
    struct musicCD
    {
        string artist, title;    // artist of the CD
    };
    //Memory allocation
    musicCD *ptr;
    try{ptr = new musicCD;}
    catch(bad_alloc){cerr << "Out of memory :(";return -1;}
    catch(...){cerr << "Something bad happened :O !";return -1;
    }

    //Get the data to store:
    cout << "Please enter the data for the CD!' " << endl;
    cout << "Please enter the artist: ";getline(cin, ptr->artist); cout << endl;
    //Write out the data
    cout << "The data entered: " << endl;
    cout << "The artist performing is: \t" << ptr->artist << endl;

    delete ptr;
    return 0;
}
  • 10
    What led you to believe that "nobody knows the size of the memory to be allocated"? That's very obvious. Sufficient memory for one instance of the `musicCd` object was needed, it was allocated, then deallocated. – Sam Varshavchik Jan 25 '17 at 16:39
  • 1
    _nobody knows the size of the memory to be allocated_ Not true. `musicCD` has a fixed size (use `sizeof` to see its size). – Algirdas Preidžius Jan 25 '17 at 16:39
  • 1
    I don't believe the standard cares, however the size of musicCD is determined by new, there are standard operations you can do to get the size, i.e. `sizeof(musicCD)` – George Jan 25 '17 at 16:40
  • 3
    On a side note, the IDE doesn't care about how much memory will / will not be allocated. The compiler on the other hand will. It's not really on topic for the question but a mistake that could lead to understanding problems later. – UKMonkey Jan 25 '17 at 16:50
  • @op I the missing part of the equation I think is that the sizeof(string) is constant. If you add content to a string the new content is managed on the heap. This means that string s("") and string t("ssjlskjskljlsj") are the same size on the stack; – london-deveoper Jan 25 '17 at 16:53
  • @ccpgh Minor niggle: C++ does not acknowledge the existence of heap and stack. Heap and stack are common implementations of the dynamic and temporary storage specified by C++. – user4581301 Jan 25 '17 at 16:58
  • as a learning experience, I will recommend you to try to implement your own object that perform some memory allocation. You can try to implement your own string object for example. – Alessandro Teruzzi Jan 25 '17 at 16:58

1 Answers1

2

It seems like you are confused about how std::string, or any dynamic container, handles the fact that it's memory requirements are not predetermined. std::string for example does not store it's character data internally. Simply put, it contains a pointer that points to another dynamic allocated buffer which contains the actual data. std::string has constructors, a destructor and assignment operators that automatically manage the extra buffer, which contains the actual character data. This including reallocating, copying the data, updating the internal pointer and freeing the previous buffer when extra storage is needed. The size of the buffer that contains the actual data does not count towards the size of std::string, only the pointer to it does. Every instance of std::string, throughout it's lifetime, only directly contains a constant number of members which all have constant sizes. In c++ all types have a compile time constant size.

See Rule of five for a simplified implementation of string showing how it works. The size of the class rule_of_five from this example is simply the size of char* regardless of the content of the buffer pointed to by this pointer. The actual buffer is allocated later, during or after construction, which is after the initial allocation for the object itself has already finished.

Edit: There are some cases where a string can store it's character data internally when dealing with very short strings. This is an optimization not generally seen in other containers. See this answer.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87