473,765 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem understanding returning a pointer and memory allocation

25 New Member
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<iostre am>
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;
}
Oct 4 '07 #1
1 1722
ilikepython
844 Recognized Expert Contributor
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<iostre am>
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;
}
In test2() you should use strcpy to assign:
Expand|Select|Wrap|Line Numbers
  1. strcpy(buf, "abcdefgh");
  2.  
In test1() I'm not sure, but I don't think you should do that.
In test() you are returning the address of a local variable so it will be destroyed when the function returns and the pointer will point to garbage. It is different from test2() because there you are allocating on the heap and it stays there until a delete call.

Maybe someone else can explain more.
Oct 4 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

18
6175
by: Ian Stanley | last post by:
Hi, Continuing my strcat segmentation fault posting- I have a problem which occurs when appending two sting literals using strcat. I have tried to fix it by writing my own function that does the strcat (mystract). Program below. However this appears not to have fixed the problem and I don't know why it shouldn't ? Any further help as to what else I am doing wrong will be appreciated regards
6
2516
by: Nick | last post by:
excuse me!! may i ask a simple problem here? if i dynamically allocate a memory(ex. new in C++ or malloc in C) in a sub-function and forget free the space end of the sub-function. does it cause memory leak or the space automatically free by OS??
57
4302
by: Xarky | last post by:
Hi, I am writing a linked list in the following way. struct list { struct list *next; char *mybuff; };
1
4103
by: Brandon Langley | last post by:
I have this structure that I am using in conjunction with NetLocalGroupAddMembers: public struct LOCALGROUP_MEMBERS_INFO_3 { public string lgrmi3_domainandname; } I am having failures that stinky hugely of either memory allocation being
7
2176
by: mef526 | last post by:
I have had this problem for months now and it has been nagging me. I have a large project that has several C++ DLL's, one of them uses malloc / calloc / free for the other DLL's. I process very large datafiles (100MB to 300 MB) that have more than 524,000 lines with 5 columns of numbers in text. I allocate 8 arrays with 524,000 or more doubles , and 10 arrays of 32,768 doubles. Is there a min size for malloc / calloc required to...
39
19646
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1) What's the difference between these 3 statements: (i) memcpy(&b, &KoefD, n); // this works somewhere in my code
11
3054
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
22
1916
by: sam_cit | last post by:
Hi Everyone, I have the following structure in my program struct sample { char *string; int string_len; };
11
3360
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible ways of passing an array. In the following code, fun1(int a1) - same as fun1(int* a1) - where both are of the type passed by reference. Inside this function, another pointer a1 is created whose address &a1 is different from that of the passed...
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7375
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.