473,741 Members | 4,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How does "delete [] <pointer>" work?

Hi everyone,

Im just starting out with C++, and am curious to know how "delete []
<pointer>", knows about the number of memory locations to free.

I read somewhere that delete frees up space assigned to <pointerby
"new". Does "new" create a list of pointer names and the size of the
memory array they point to? I also read that some compilers may store
the number of consec mem locations a pointer points to, just before the
first data element. Is that correct?

Also, if i used malloc() to make <pointerpoint to a number of memory
locations, will calling "delete [] <pointer>" still work? if yes, how
does delete here know the number of memory locations to free? does the
malloc() implementation in C++ also create a pointer/memsize list like
"new"?

And lastly, if i made another pointer <pointer2poin t to the same
location as <pointer>, would calling "delete [] <pointer2>" still free
up the correct number of locations?

Thanks in advance for answering my deluge of questions!
regards,
Mayank

Aug 20 '06 #1
5 8090
mkaushik wrote:
Hi everyone,

Im just starting out with C++, and am curious to know how "delete []
<pointer>", knows about the number of memory locations to free.
The answer is implementation dependent.
I read somewhere that delete frees up space assigned to <pointerby
"new". Does "new" create a list of pointer names and the size of the
memory array they point to? I also read that some compilers may store
the number of consec mem locations a pointer points to, just before the
first data element. Is that correct?
In general, that's how it works, but you can't rely on it. Each
implementation has its own methods.
>
Also, if i used malloc() to make <pointerpoint to a number of memory
locations, will calling "delete [] <pointer>" still work?
No. If you malloc() it, free() it. If you "new" it, "delete" it. If
you "new[]" it, "delete[]" it. It's that simple.

if yes, how
does delete here know the number of memory locations to free? does the
malloc() implementation in C++ also create a pointer/memsize list like
"new"?
Many implementations of operator new call malloc behind the scenes, but
it is not required. Again, it's implementation dependent. Besides, you
can't delete[] memory allocated with malloc.
And lastly, if i made another pointer <pointer2poin t to the same
location as <pointer>, would calling "delete [] <pointer2>" still free
up the correct number of locations?
int* p = new int[30];
int* p2 = p;
delete[] p2;

Is valid, but dangerous, as p now points at unallocated memory.
Accessing anything through p (or p2) is undefined behavior.

Aug 20 '06 #2
In article <11************ **********@m79g 2000cwm.googleg roups.com>,
pr************* **@yahoo.com says...
Hi everyone,

Im just starting out with C++, and am curious to know how "delete []
<pointer>", knows about the number of memory locations to free.
It's required to do so, but exactly how it does so is up to the
implementation.
I read somewhere that delete frees up space assigned to <pointerby
"new". Does "new" create a list of pointer names and the size of the
memory array they point to? I also read that some compilers may store
the number of consec mem locations a pointer points to, just before the
first data element. Is that correct?
In both cases, the answer is a definite maybe -- it can keep track of
all of the data in one place, or it can put data in each node as it's
allocated, or whatver else it prefers.
Also, if i used malloc() to make <pointerpoint to a number of memory
locations, will calling "delete [] <pointer>" still work?
If you use malloc to allocate some memory and then use delete on that
memory, the results are undefined -- it might work for some sufficiently
loose definition of "work". Then again, it might simply crash and burn,
or it might do just about anything else.
if yes, how
does delete here know the number of memory locations to free? does the
malloc() implementation in C++ also create a pointer/memsize list like
"new"?
It could, but it's not required to do so -- allocating memory with
malloc and then attempting to delete it isn't required to work at all.
And lastly, if i made another pointer <pointer2poin t to the same
location as <pointer>, would calling "delete [] <pointer2>" still free
up the correct number of locations?
If I understand your question correctly, yes. What you get back from new
is an address. You have to pass that address to delete exactly once --
but the pointer you store the address is makes no difference at all.

To summarize: if you use new to allocate some memory, you must use
delete exactly once on the address you get from new. If you use new[] to
allocate the memory, you must use delete[] exactly once on that address.
If you allocate some memory with malloc, you must call free exactly once
with that address malloc returned.

Beyond that, exactly how each of these accomplishes what it's supposed
to is up to the implementer. When you do something like:

struct whatever {
whatever() { std::cout << "ctor\n"; }
~whatever() { std::cout << "dtor\n"; }
};

whatever *w = new whatever[10];
// ... other stuff here

delete [] whatever;

The 'new' is reuqired to use whatever's ctor to create each of the ten
objects, and the delete is required to use whatever's dtor to destroy
each of those ten objects. How it knows there are ten objects to destroy
is entirely up to it. It might allocate some extra memory and store it
along with the object. It might have a separate table of sizes of
objects. It's even possible that it could (for one example) use the
exact value of the pointer to tell it what it needs -- assuming, for the
moment, a CPU that had no alignment requirements, it could (for one
example) make some bits in the address it assigns equal to the size of
the array that was allocated. Obviously this has the potential for
wasting some address space, but on (for one example) a machine with 64-
bit addressing, that's not likely to be a problem at least in the near
future.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 20 '06 #3
In article <MP************ ************@ne ws.sunsite.dk>,
jc*****@taeus.c om says...

[ ... ]
whatever *w = new whatever[10];
// ... other stuff here

delete [] whatever;
Oops -- that should (of course) be:

delete [] w;

Sorry 'bout that.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 20 '06 #4
In article <11************ **********@m79g 2000cwm.googleg roups.com>,
mkaushik <pr************ ***@yahoo.comwr ote:
>Im just starting out with C++, and am curious to know how "delete []
<pointer>", knows about the number of memory locations to free.

I read somewhere that delete frees up space assigned to <pointerby
"new". Does "new" create a list of pointer names and the size of the
memory array they point to? I also read that some compilers may store
the number of consec mem locations a pointer points to, just before the
first data element. Is that correct?
Exactly how it works is implementation defined, so yes, that's
one allowed possibility as I recall.
>Also, if i used malloc() to make <pointerpoint to a number of memory
locations, will calling "delete [] <pointer>" still work? if yes, how
does delete here know the number of memory locations to free? does the
malloc() implementation in C++ also create a pointer/memsize list like
"new"?
It may work, but generally a bad idea; most likely it'll crash,
or appear to work only for something seemingly unrelated to fail later.
Normally you want to stay in the same deallocation family that you
allocated from. So malloc/free, new/delete, new[]/delete[],
class new/delete / new[]/delete[] respectively. "placement new"
has its own concerns too.
>And lastly, if i made another pointer <pointer2poin t to the same
location as <pointer>, would calling "delete [] <pointer2>" still free
up the correct number of locations?
Absolutely. Just make sure your code doesn't use either after
that point though because they'd be invalid pointers unless
reassigned, etc.
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in alpha!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 20 '06 #5
mkaushik wrote:
I read somewhere that delete frees up space assigned to <pointerby
"new". Does "new" create a list of pointer names and the size of the
memory array they point to? I also read that some compilers may store
the number of consec mem locations a pointer points to, just before the
first data element. Is that correct?
See also
http://www.parashift.com/c++-faq-lit...html#faq-16.14

Phil
Aug 21 '06 #6

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

Similar topics

22
3346
by: Dr Duck | last post by:
GDay all, Something seems odd to me.... I wrote a simple C# function public void bind(ref object a, ref object b, bool atob) { if(atob) b = a; else
3
2247
by: Piotre Ugrumov | last post by:
I have done the overload on the operator >> and << in the class Attore. These 2 overload work correctly. I have done the overload of the same overload in the class Film. The class film ha inside an array of pointer to Attore. I have written these overload in these ways. the overload of << work correctly the overload of >> I don't know. I compile the class correctly, when I insert a film through the operator >> I don't receive error, but...
10
67763
by: Eric-Sebastien Lachance | last post by:
Hey there, I decided to just create a 100% height and width div that filled the space over a background header image, and add an onclick event to redirect to the my index... Doesn't seem to work in FireFox only, just in IE. Here's the code: <div id="headerimg"><div style="width: 100%; height: 100%; cursor: hand; cursor: pointer;" onclick="top.location.href('http://www.monamouchtim.com/');">&nbsp;</div></div>
20
2205
by: Oliver S. | last post by:
I was often annoyed about the performance of std::basic-string because of complex memory-allocators working in the background to found the work of std::allocator<T>. Basically, the performance doesn't reeach the per- formance of a stack-based C-string in most cases. But nevertheless, the comfort and the implicit protection against buffer-overflows makes std:: basic_string woth to be used. So I searched for a way to have my own stack-based...
3
3505
by: Evgeny | last post by:
Hi, all! I didn't find yet solution for this problem! Somebody knows where is a catch? Looks like "operator =" or copy constructor not implemented in one of internal templates.... Thanks in advance class CMyBase;
16
2405
by: call_me_anything | last post by:
why is the following not allowed : vector <Base *vec_of_base; vector <Derived *vec_of_derived; vec_of_base = vec_of_derived; Note : The following is allowed :
232
13311
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
1
1642
tekninja
by: tekninja | last post by:
I wanted to write a function to take the tedium out of dynamically determining the total number of elements in an array. Within the main method this is easy as I simply use: sizeof( <array name> ) / sizeof( <array type> ) However I am running into an annoying problem when trying to pass an array reference to a function that is suppossed to return the same value as the above would. my function reads: int numElements( int array ){ ...
43
4821
by: john | last post by:
Hi, in TC++PL 3 on pages 674-675 it is mentioned: "Maybe your first idea for a two-dimensional vector was something like this: class Matrix { valarray< valarray<doublev; public: // ... };
0
9484
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...
1
9272
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
9211
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
8218
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
4572
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
4826
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3286
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
2751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2195
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.