473,705 Members | 6,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about scope of variables created with new

Lets say I have a program:

#include <iostream>
#include <conio.h>
using namespace std;

int* ptest();

int main()
{
int* b = ptest();
getch();

return 0;
}

int* ptest()
{
int num = 5;
int* intp = new int(num);

return intp;
}

Is there any way to free the memory that was allocated for the variable
intp outside of the function, ptest()? Thanks

Jul 23 '05 #1
10 1470
africamp wrote:
Lets say I have a program:

#include <iostream>
#include <conio.h>
using namespace std;

int* ptest();

int main()
{
int* b = ptest();
getch();

return 0;
}

int* ptest()
{
int num = 5;
int* intp = new int(num);

return intp;
}

Is there any way to free the memory that was allocated for the variable
intp outside of the function, ptest()? Thanks


Of course. Just do:

delete b;

within main.
Jul 23 '05 #2
but doesn't that just deleter the pointer to the integer and not the
integer itself?

Jul 23 '05 #3
"africamp" <af******@gmail .com> wrote...
but doesn't that just deleter the pointer to the integer and not the
integer itself?


No, 'delete' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the 'delete'
where to find the object and the memory. The pointer itself survives.

V
Jul 23 '05 #4
"Victor Bazarov" <v.********@com Acast.net> wrote in
news:K_******** ************@co mcast.com:
"africamp" <af******@gmail .com> wrote...
but doesn't that just deleter the pointer to the integer and not the
integer itself?


No, 'delete' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the 'delete'
where to find the object and the memory. The pointer itself survives.


....and should be reset to NULL for safety

Alan
Jul 23 '05 #5
In article <Xn************ **********@211. 29.133.50>,
Alan Brown <ri*****@yahoo. nospam.com.au> wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in
news:K_******* *************@c omcast.com:
"africamp" <af******@gmail .com> wrote...
but doesn't that just deleter the pointer to the integer and not the
integer itself?


No, 'delete' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the 'delete'
where to find the object and the memory. The pointer itself survives.


...and should be reset to NULL for safety


....even though it doesn't gain you much safety, unless you can be
absolutely certain that it's the only pointer to the just-deleted object
that exists.

But it only "survives" in that the pointer object[1] still exists and
you can point it at something else - the actual value of the pointer
can no longer be safely used.
dave

[1] This is "object" in the C sense of "region of storage containing a
value", not in the OO sense of "thing with state and behavior".

--
Dave Vandervies dj******@csclub .uwaterloo.ca

ERT is correct. (For reasons I won't go into, this is worth pointing out.)
--Keith Thompson in comp.lang.c
Jul 23 '05 #6

"Alan Brown" <ri*****@yahoo. nospam.com.au> skrev i en meddelelse
news:Xn******** **************@ 211.29.133.50.. .
"Victor Bazarov" <v.********@com Acast.net> wrote in
news:K_******** ************@co mcast.com:
"africamp" <af******@gmail .com> wrote...
but doesn't that just deleter the pointer to the integer and not the
integer itself?
No, 'delete' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the 'delete'
where to find the object and the memory. The pointer itself survives.


...and should be reset to NULL for safety


This is only rarely correct.

/Peter
Alan

Jul 23 '05 #7
Alan Brown wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in
news:K_******** ************@co mcast.com:
"africamp" <af******@gmail .com> wrote...
but doesn't that just deleter the pointer to the integer and not the
integer itself?


No, 'delete' destroys the object, then deallocates the memory that was
used for that object. The pointer value is used to tell the 'delete'
where to find the object and the memory. The pointer itself survives.


...and should be reset to NULL for safety


Actually, I think it shouldn't in most places. If you have an erroneous
double-deletion, it will still be if you set the pointer to NULL. You just
happened to cure the symptoms, not the disease.

Jul 23 '05 #8
africamp wrote:
but doesn't that just deleter the pointer to the integer and not the
integer itself?


No. You should read up in your book about memory management. It works a lot
different from what you think. delete takes a pointer to a dynamically
allocated object and destroys that object. You cannot manually destroy
local variables (like your pointer) at all.

Jul 23 '05 #9
"africamp" <af******@gmail .com> writes:
int* ptest()
{
int num = 5;
int* intp = new int(num);

return intp;
}

Is there any way to free the memory that was allocated for the variable
intp outside of the function, ptest()? Thanks


Of course,just to
delete intp;
However,if the memory was allocated by you but another one should
free it.You MUST write a document to told him that the return value of
ptest() point to a int value, NOT int[].
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2557
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
7
2205
by: Jason Huang | last post by:
Hi, The SQL string is "select * from Customer where 0 > 1", and the DataSet should be null. Why MyDataSet.Tables.Count is 1, not 0? What kind of DataTable in this place? Thanks for help. Jason
10
1883
by: John Salerno | last post by:
Here's a sentence from Learning Python: "Names not assigned a value in the function definition are assumed to be enclosing scope locals (in an enclosing def), globals (in the enclosing module's namespace) or built-in (in the predefined __builtin__ names module Python provides." I have trouble reading this sentence. First, I don't understand if the word 'enclosing' is a verb or an adjective. The whole flow of the sentence seems...
4
343
by: Diffident | last post by:
Hello All, I have a question which is pertinent to Page's lifecycle. I declared a protected static object (global variable within that class) whose value is set only once when the page is loaded. Will that object's value be accessible during consequent postbacks or is it set to null after HTML is rendered initially?
7
1875
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that shows the alert. What is the essential reason? function () { alert('hi mom'); }(); function () { alert('hi dad'); }(8); var x=function () { alert('hi bro'); }();
4
1475
by: emailscotta | last post by:
Below are some over simplified examples of code the create a single instance of an object and I was hoping some one could give me the pros and cons of each approach. First declaration: In this case a single object is created using object literal notation and both the get and __Private methods are availabile for use and no closure is created. ABC.Util.SomeObject = {
1
25689
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that variable can only be used in that function. If you were to try to access that variable anywhere else in...
2
2167
by: Gabe Moothart | last post by:
Hello, In one of my asp.net applications, I create a series of checkboxes, set their properties, and give them an "onChecked" event handler on the fly using an anonymous method. The code looks like this: protected void Page_Load(object sender, EventArgs e) { Dictionary<Guid, stringdataHash = ... //db access foreach(KeyValuePair<Guid, stringrow in dataHash) {
20
4038
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
4
1312
dmjpro
by: dmjpro | last post by:
Today i looked at JavaScript closures. There i came across a thing closure comes in when an inner function defined inside an outer function. So when outer function exits and returns the inner function reference then a hidden reference returns along with the reference of inner function. Now my question is when that hidden reference created? And the hidden reference have the references of all local variables of outer function. Now my second...
0
9274
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9139
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
8979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7895
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...
0
4440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3138
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
2491
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2083
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.