473,602 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new and delete question

Hi,

I am new to C++, and I have a simple question but I can't seem to find
a direct answer.

If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?

In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.

Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?

Thanks

Feb 10 '07 #1
6 1879
* md*****@gmail.c om:
>
I am new to C++, and I have a simple question but I can't seem to find
a direct answer.

If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
Yes, but only due to bugs in your program. ;-)

A (raw) pointer is very low-level kind of object in C++. It has no
automatic behavior. Nothing happens when a pointer variable goes out of
scope.

If you have copied the pointer value somewhere, and that value refers to
dynamically allocated memory, you still have access to that memory.

To avoid pointer bugs, simply don't use raw pointers directly.

Use smart pointers such as std::auto_ptr and boost::shared_p tr.

In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.
See above.

Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?
Normally you don't call destructors manually. An object's destructor is
automatically called when you 'delete' something you 'new'ed, or for an
automatic (local) variable, when execution leaves the defining scope.
Note that for an automatic (local) raw pointer variable, nothing
happens: the variable itself has no destructor, no automatic behavior,
even if the pointed to object has.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 10 '07 #2
md*****@gmail.c om wrote:
Hi,

I am new to C++, and I have a simple question but I can't seem to find
a direct answer.

If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
No. Memory allocated by new will remain valid until deallocated by delete.
In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.
That will happen.
Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?

For a non-dynamic object (not created by new), the destructor will
automatically invoked when the object goes out of scope. For an object
allocated with new, the destructor will be invoked when you delete it.

There are only a couple of edge cases where you need to manually call a
destructor, and since you're a newbie, you should not hit those
(placement new).
Feb 10 '07 #3
md*****@gmail.c om wrote:
Hi,

I am new to C++, and I have a simple question but I can't seem to find
a direct answer.

If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
No.
In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.
The pointee will not go away without an explicit delete.

Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?
Destructors of object are called automatically if the objects go out of
scope. Also, when you do

delete p;

the destructor for the pointee *p will be called automatically. Note that in
a scope like

{
T* p;
p = new T (...);
...
delete p;
}

this does not involve calling any destructor twice: delete p; calls the
destructor for type T on the object *p whereas the pointer p going out of
scope calls the destructor for type T* on the object p (this destructor is
a null-op, as far as I know).
BTW: are you sure you want to use raw pointers? They are a pain and hard to
use correctly (mostly because it is very difficult to match every new with
one and only one delete along _each_ possible path of flow control: think
of how exceptions might divert the path of execution to some unknown target
location!).
Best

Kai-Uwe Bux
Feb 10 '07 #4

md*****@gmail.c om wrote:
>
If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
You need to learn about basic memory types in C/C++ programs. Whithout it it
will be hard for you to program. Any free book about C++ in the inet can
tell you about. It is not newsgroup topic, for has no C++ specific
limitations.

--
Maksim A. Polyanin

"In thi world of fairy tales rolls are liked olso"
/Gnume/
Feb 11 '07 #5

Grizlyk wrote:
>
It is not newsgroup topic, for has no C++ specific limitations.
I want to say, that you can not learn C++ from newsgroup, you need large,
more based and detailed explanations, that can be found only in books or
manuals.
--
Maksim A. Polyanin

"In thi world of fairy tales rolls are liked olso"
/Gnume/

Feb 11 '07 #6
On 10 Feb, 16:03, mdin...@gmail.c om wrote:
Hi,

I am new to C++, and I have a simple question but I can't seem to find
a direct answer.
What you are asking might seem simple, but as soon as you scratch the
surface you will realise it is anything but. You are asking about an
advanced part of C++.
If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
No, you can be sure that the object will continue to exist until you
delete it. That is the problem. If you use new to create something in
the scope of a function and then you return the pointer that you get
to another function, you do not need to worry about the memory space
being used by anything else and causing the program to crash? But
that's the easy part. What you do need to worry about is the hard
part:

You need to be certain that in all current and likely future uses of
your function, the new'ed pointer is deleted no less than and no more
than once.
You need to be certain that any and all possibilities for copying,
modifying, passing the pointer do not violate the above point.
You need to be certain that the above two points hold, both throughout
the normal flow of execution, and in the presence of exceptions.
In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.
That is something you can be sure of. However, it should not be what
you are trying to ensure. Not calling delete until you have finished
with the object is easy. Ensuring that delete is still called, exactly
once, regardless of the path taken through the code (including the
path taken if an exception is thrown at any point) is much harder. You
should be trying to ensure that ownership semantics are clear and
unambiguous, and are not likely to introduce bugs as code is modified.

As someone new to C++, you shouldn't be worrying about manually
managing ownership. You should be using classes that manage that for
you. Read about smart pointers and the RAII concept.
Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?
For objects with automatic or static storage duration (roughly, local
and global variables respectively), your compiler will take care of
calling destructors when required. For objects with dynamic storage
duration (i.e. objects allocated with new or new[]) nothing happens
automatically. You, and you alone, are responsible for ensuring that
each and every new is paired with one and only one delete, and that
each and every new[] is paired with one and only one delete[].

The need for that certainty and the difficulty in achieving it is the
reason why things like smart pointers were invented.

Gavin Deane

Feb 11 '07 #7

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

Similar topics

6
2428
by: Matan Nassau | last post by:
Hello. i have a composite which i want to delete. this is a composite which represents a boolean expression (see a previous post of mine with more details at http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&threadm=AXqqc.89218%24PJ1.865449%40wagner.videotron.net&rnum=1&prev=/groups%3Fq%3Dmatan%2Bnassau%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DG%26scoring%3Dd ) VariableExp *x = new VariableExp("X"); VariableExp *y = new VariableExp("Y");...
16
3863
by: robert | last post by:
been ruminating on the question (mostly in a 390/v7 context) of whether, and if so when, a row update becomes an insert/delete. i assume that there is a threshold on the number of columns of the table, or perhaps bytes, being updated where the engine just decides, screw it, i'll just make a new one. surfed this group and google, but couldn't find anything. the context: we have some java folk who like to parametize/
0
2260
by: Suzanne | last post by:
I'd like to know how can I put up a confirmation question when the user tries to delete a row in the datagrid by clicking on the row header and pressing the Delete key? I have found this code on a windows forms FAQ site : Public Class DataGrid_Custom Inherits DataGrid Private Const WM_KEYDOWN = &H100
1
8562
by: Barry L. Camp | last post by:
Hi all, Wondering if someone can help with a nagging problem I am having using a GridView and an ObjectDataSource. I have a simple situation where I am trying to delete a row from a table, but it doesn't seem to work at all. Below is my ASP.NET page, and further below, my VB.NET method that I am trying to call: <div id="admin-faq" class="page"> <h2>Site FAQs (Frequently Asked Questions)</h2>
12
3362
by: yufufi | last post by:
Hello, How does delete know how much memory to deallocate from the given pointer? AFAIK this informations is put there by new. new puts the size of the allocated memory before the just before the beginning of the array. But I couldn't find this information by looking at the memory. (Via VS2005 - C++) My second questions is, if there is a mechanism to know how much memory is allocated for the array, why don't we use it for things like...
10
2083
by: jeffjohnson_alpha | last post by:
We all know that a new-expression, foo* a = new foo() ; allocates memory for a single foo then calls foo::foo(). And we know that void* p = ::operator new(sizeof(foo)) ; allocates a sizeof(foo)-sized buffer but does NOT call foo::foo().
15
1777
by: tom | last post by:
why delete the dynamically allocated memory twice causes an error, see the code below: int _tmain(int argc, _TCHAR* argv) { int *pi = new int(12); cout<<*pi; delete pi; delete pi; }
29
2245
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I remembered delete is implemented through operator overloading, but I am not quite clear. Could anyone recommend some links about how delete is implemented so that I can learn and refresh my memory? :-)
7
1809
by: subramanian100in | last post by:
The following discussion is for learning purpose only. 1) Suppose for a type T, I have T *ptr = new T; To free ptr, suppose I use ( I deliberately omit in delete.) delete ptr;
18
3652
by: aj | last post by:
I have the following snippet of code. On some platforms, the delete calls works, on Linux, it core dumps (memory dump) at the delete call. Am I responsible for deleting the memory that gethostbyname allocated? struct hostent *lHostInfo; lHostInfo = gethostbyname(ipHost.c_str()); memcpy(&(lDestAddr.sin_addr), lHostInfo->h_addr_list, lHostInfo- delete lHostInfo;
0
7993
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
8401
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
8404
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...
1
8054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6730
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
5867
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
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2418
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
0
1254
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.