So, I'm dynamically allocating a char array in a function, then returning that array to an un-allocated char array in main().
Code:
#include<iostream>
using namespace std;
char* cc(char*,char*);
int main(){
char* strMain;
char* str1="Well, hello there, ";
char* str2="How are you?";
strMain=cc(str1,str2);
cout<< strMain;
}
char* cc(char* str1,char*str2){
char* retVal;
int i=0,len=0;
while(str1[len]!='\0'){
len++;
}
while(str2[i]!='\0'){
len++;
i++;
}
retVal=new char[len];
i=0;
while(str1[i]!='\0'){
retVal[i]=str1[i];
i++;
}
len=0;
while(str2[len]!='\0'){
retVal[i]=str2[len];
len++;
i++;
}
return retVal;
}
will strMain become the reference for the block of memory allocated in the cc function as retVal?
If I delete[] strMain, will that be the same as freeing the memory I allocated in cc()?
Oh, second question,
if I go
char* variable="hello world!";
char* variable2;
variable2=new char[13];
variable2="hello world!";
what's the difference between how variable and variable 2 are stored?
My understanding is, variable is stored on the stack and will be pop'd automatically when it goes out of scope, whereas variable2 is allocated in a block of memory reserved for my program ("heap") and will stay there even if I lose the reference to it. Is this correct? How is the "heap" created? Do I just get some memory from the system when I allocate memory? Or is there a limited block of memory already there, and that's all I'm allowed to use? If the latter, how does one control the size of the "heap?"