In the following code, I am trying to return a char[], a char* (a type of non-const without using new, what do we call this type of pointer?) and char* created using new operator. What I do not know at all is how variables are created in what type of memory and how they are deleted in the following three cases when calling and exiting test, test1 and test2 functions.
I also note that I see a different result while using char[] and char* which I thought were the same. I return char[] in test seems to be deleted once test is exited and char* in test1 seems to return a memory location and value which is same as that being accessed in main(). I always thought that the variables are deleted and including the pointers other than those created using new operator. Any help about basics of the memory allocation in these cases is appreciated.
#include<iostream>
using namespace std;
long int tmpAddStorage;
char* test2()
{
char* buf = new char[10];
buf = "abcdefgh";
cout << "In test1 using dyn mem allocation: (int *)buf" << (int *)buf << endl;
return buf;
}
char* test1()
{
char* buf = "abcdef"; // created in its temporary memory ??
cout << "In test1 using char* buf creation" << endl << " (int *)buf" << (int *)buf << endl;
//delete buf; // NO USE: delete must be followed by a poitner created using new
// and not pointer to a const, however, delete buf does not
// throw an error nor does it create any change
return buf; // same as return buf;
}
char* test()
{
char buf[] = "abcdef"; // created in its temporary memory
cout << "In test() using char buf[] creation" << "(int *)buf" << (int *)buf << endl;
return (char *)buf; // same as return buf;
// warning address of local variable buf is returned
}
int main() {
char* p ;
//***********************
p = test(); // I know that this call is useless. So I tried to modify the
// test() function to return the char * properly. I listed my
// solution down below. Please feel free to advise.
cout << "(int *)p " << (int *)p << endl;
// points to the same memory location but this time it is empty because
// test() has returned
cout << "p " << p << endl;
//***********************
//***********************
p = test1(); // returning a char* in test1()
cout << "(int *)p " << (int *)p << endl;
cout << "p " << p << endl;
//***********************
//***********************
p = test2(); // using dyanmic memory allocation in test1()
cout << "(int *)p " << (int *)p << endl;
cout << "p " << p << endl;
//***********************
//So can we modify something in a different function if we know its address?
// How can we store an address and modify the contents in its location?
// int a = 20;
// cout << &a << endl;
// tmpAddStorage = (int)&a;
// cout << hex << tmpAddStorage << endl;
delete p;
system("pause");
return 0;
}