Reputation: 731
Let's say char array of 100 is made and a short string is allocated inside it.
Ex)
char a[100];
sprintf(a,"%d sized char",100);
string str(a);
(I know i can a[] = "some string"; but this is not the case and thing that im concerned with)
Then where does rest of the memories go? str wouldnt be saved with string and spaces behind it. Are they freed(?) Or ignored during conversion from char [] to str?
Btw. Can you also introduce me a reference or book to memories? I'm a heginner but they interest me but i can't get infos about them easily.
Upvotes: 0
Views: 89
Reputation: 21627
When you do
char a[100] ;
you are allocating 100 bytes.
If you do this as a local variable
void somefunct () ;
{
a[100] ;
}
The memory allocated to A will automatically be reclaimed. The allocation is made on the system stack.
Before calling somefunc ()
^ [Stack Memory Here]
[SP]
while executing some function()
A [Old SP Value]
[SP]
When somefunct completes
^ [A was out here]
[SP]
If you do it
a[100] ;
void somefunct () ;
{
}
The memory will remain allocated.
When you do
string str(a) ;
str makes a copy of the contents of A "100 sized char".
Also note that your string "%d sized char" also takes up memory that will not be deallocated.
Upvotes: 1
Reputation: 1980
string
manages its part of the memory. When you do the conversion, string
will copy your string. Notice that your a
is not null terminated, might result in problems
Upvotes: 1