473,756 Members | 6,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

use delete to destroy primitive/object types but memory is not freed

Hello,

This is a simple question for you all, I guess .
int main(){
double *g= new double;
*g = 9;
delete g;
cout<< sizeof(g)<<" "<<sizeof(doubl e)<<" "<<sizeof(*g)<< " "<<*g<<" "<<endl;
*g = 111;
cout<< sizeof(g)<<" "<<sizeof(doubl e)<<" "<<sizeof(*g)<< " "<<*g<<" "<<endl;
return 0;
}

The output:
4 8 8 9
4 8 8 111

Although I delete g, why is it that I can still use it and it references to
actual memory?

The same happens when creating and deleting object types with new and
delete!

Please dont answer with what you think but with what actually happens. If
you can point me to web sources I can read on this, it would have been
great!

Thank you in advance.
Regards,
jimjim
Nov 14 '05
30 3743
> hen you're off-topic, you're off-topic. Don't argue about it, just take
the good advice you are given.

I cant understand why if I am off topic an answer exists in the C-faq. Of
course for the C equivalent of the C++ code I provided in my original post.
Take few steps back and look at the bigger picture please (Dont take it that
I am trying to be "clever" now please)
Even if the simple substitution you propose actually worked (it doesn't)
int main(){
int *g= malloc(sizeof(i nt));
*g = 9;
free(g);
printf("%d %d %d %d\n",sizeof(g) ,sizeof(double) ,sizeof(*g),*g) ;
*g = 111;
printf("%d %d %d %d\n",sizeof(g) ,sizeof(double) ,sizeof(*g),*g) ;
return 0; }

The above substitution gives me the same results. Please why dont you try to
explain to me what exactly you mean? This is a typical phainomenon in
newsgroups; people having the knowledge to answer but provide cryptic
answers. If you are not to give a clear answer to my question, its better
not to answer at all!
there are still differences between C and C++ memory allocation, and

comp.lang.c++ is where you'll get the right >answers, reviewed by the right
people.

Can you please explain to me what is the case in C. This is again a genuine
question. I just want to learn!

Nov 14 '05 #11
ha, that was such a good example!!

Thank you :-)
Nov 14 '05 #12
"jimjim" <Fr*********@bl ueyonder.co.uk> wrote in message
news:uO******** *************@n ews-text.cableinet. net...
Even if the simple substitution you propose actually worked (it
doesn't)
int main(){
int *g= malloc(sizeof(i nt));
*g = 9;
free(g);
printf("%d %d %d %d\n",sizeof(g) ,sizeof(double) ,sizeof(*g),*g) ;
*g = 111;
printf("%d %d %d %d\n",sizeof(g) ,sizeof(double) ,sizeof(*g),*g) ;
return 0; }
Do you mean *g to be an int or a double? Mixing types the way you've done
is not portable and will not work on at least one popular architecture.
The above substitution gives me the same results. Please why dont you try to explain to me what exactly you mean? This is a typical phainomenon in
newsgroups; people having the knowledge to answer but provide cryptic
answers. If you are not to give a clear answer to my question, its better
not to answer at all!


free() is not required to release memory immediately, nor is it required to
make that memory somehow inaccessible; on most implementations it's
impossible to do that at the granularity of a single int. For example, on
unix-like systems it's common that memory can only be requested from or
released to the OS in page-sized (typically 4kB) blocks and release must be
done in LIFO order.

Accessing freed memory explicitly causes Undefined Behavior, which may in
most cases do what you expect it to do. Or it might not -- that's why it's
called "undefined" .

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin
Nov 14 '05 #13
Stephen Sprunk wrote:
free() is not required to release memory immediately
nor is it required to make that memory somehow inaccessible;
on most implementations ,
it's impossible to do that at the granularity of a single int.
For example, on unix-like systems it's common that
memory can only be requested from or released to the OS
in page-sized (typically 4kB) blocks
and release must be done in LIFO order.

Accessing freed memory explicitly causes Undefined Behavior,
which may in most cases do what you expect it to do.
Or it might not -- that's why it's called "undefined" .


You're off-topic and out of your depth here.
The way that the OS acquires physical memory for processes
is transparent to allocating free storage in your C program.
The typical implementation of free storage is a free list
and it can and often does allow the program to allocate and free
memory at the granularity of a single int.
My GNU C compiler, for example, does this.

Nov 14 '05 #14
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
jimjim wrote:
This is a simple question for you all, I guess .
int main(){
double *g = new double;
double* g = (double*)malloc (sizeof(double) );
*g = 9;
delete g;


free((void*)g);
cout<< sizeof(g)<<" "<<sizeof(doubl e)<<" "<<sizeof(*g)<< " "<<*g<<" "<<endl;


fprinf(stdout, ...
*g = 111;
cout<< sizeof(g)<<" "<<sizeof(doubl e)<<" "<<sizeof(*g)<< " "<<*g<<" "<<endl;


fprintf(stdout, ...
return 0;
}


What a mess. Try this:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
double *g = malloc(sizeof *g);

*g = 9;
free(g);

printf("sizeof g = %d, sizeof(double) = %d, sizeof *g = %d\n",
(int)sizeof g, (int)sizeof(dou ble), (int)sizeof *g);
*g = 111;

/*
* Note: There's no much point in repeating the printf;
* there's no way the sizes can change.
*/
printf("sizeof g = %d, sizeof(double) = %d, sizeof *g = %d\n",
(int)sizeof g, (int)sizeof(dou ble), (int)sizeof *g);

return 0;
}

When I run this, I get:

sizeof g = 4, sizeof(double) = 8, sizeof *g = 8, *g = 9
sizeof g = 4, sizeof(double) = 8, sizeof *g = 8, *g = 111
delete's or free's the object to which g points.
g is still a valid [pointer] object
but the object to which it points is *not*.
Any reference to *g is *undefined* --
not defined by either the C or C++ standards
after *g is delete'd or free'd.


After the call to free(g), any reference to *g invokes undefined
behavior. Also, any reference to g, the pointer variable, invokes
undefined behavior, even if you don't dereference it. Although the
call to free() isn't going to change the bits that make up the value
of g, that value becomes invalid; even comparing g to another pointer
value invokes undefined behavior.

Of course, undefined behavior is a tricky thing; it can, and often
does, manifest itself as the program doing exactly what you think it
should. (Murphy's law, which is outside the scope of the C standard,
implies that it will then stop working at the most inconvenient
possible moment.)

After you've called free(g), you can assign a new value to g:

g = malloc(sizeof *g);
... /* g is now valid */
free(g);
... /* g is now invalid */
g = malloc(sizeof *g);
... /* g is now valid again */

This is allowed because it assigns a new value to g without referring
to the previous value.

C and C++ are two different languages, and we really can't discuss C++
here in comp.lang.c. If you want to discuss C++, feel free to do so
in one of the C++ newsgroups.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #15
jimjim wrote:
ha, that was such a good example!!

Thank you :-)


In the general case, following Trollsdale's example will only lead to
pain and sloppy code.

--
yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
To email me, rot13 and convert spelled-out numbers to numeric form.
"Makes hackers smile" makes hackers smile.

Nov 14 '05 #16
Keith Thompson wrote:
After the call to free(g),
any reference to *g invokes undefined behavior.
Also, any reference to g, the pointer variable,
invokes undefined behavior, even if you don't dereference it.
Although the call to free() isn't going to change the bits
that make up the value of g,
It can't. g is passed by value.
that value becomes invalid;
That's meaningless.
even comparing g to another pointer value invokes undefined behavior.
Even if *g has not been free'd.
Of course, undefined behavior is a tricky thing;
it can, and often does, manifest itself
as the program doing exactly what you think it should.
No. Undefined behavior
is simply behavior not defined by the ANSI/ISO C [89]9 standard.
The behavior may be defined by the implementation,
the computer architecture, the operating system or some other standard.
(Murphy's law, which is outside the scope of the C standard,
implies that it will then stop working
at the most inconvenient possible moment.)
Not if the behavior is defined
by something besides the ANSI/ISO C [89]9 standard.

C is used to write platform specific applications such as
device drivers, operating system kernels and standard C libraries.
It is neither practical or desirable to comply
with the ANSI/ISO C standards in such applications.
After you've called free(g), you can assign a new value to g:

g = malloc(sizeof *g);
... /* g is now valid */
free(g);
... /* g is now invalid */
g = malloc(sizeof *g);
... /* g is now valid again */
But you said, "Also, any reference to g, the pointer variable,
invokes undefined behavior, even if you don't dereference it."

Doesn't

g = malloc(sizeof *g);

reference g?
This is allowed because it assigns a new value to g
without referring to the previous value.
That's not the same thing as "referencin g g".
C and C++ are two different languages,
and we really can't discuss C++ here in comp.lang.c.
That's your opinion. You're welcome to it.
But I don't share it.
If you want to discuss C++,
feel free to do so in one of the C++ newsgroups.


That's religious intolerance. I don't share your bigotry.
If you don't want to discuss C++, please ignore all references to C++.
Just snip them out of your replies.

Nov 14 '05 #17
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
Keith Thompson wrote:
After the call to free(g),
any reference to *g invokes undefined behavior.
Also, any reference to g, the pointer variable,
invokes undefined behavior, even if you don't dereference it.
Although the call to free() isn't going to change the bits
that make up the value of g,
It can't. g is passed by value.


Right.
that value becomes invalid;


That's meaningless.


No, it isn't, though my use of the term "invalid" was somewhat
informal. Recall that g is a pointer to double. The call free(g)
causes the allocated double object (which can be referred to as *g) to
reach the end of its lifetime. C99 6.2.4p2 says:

The value of a pointer becomes indeterminate when the object it
points to reaches the end of its lifetime.

Attempting to refer to an indeterminate value causes undefined
behavior. (In most implementations , this won't actually cause any
problems, but the standard allows it to become a trap representation,
and referring to the pointer value could conceivably crash the
program. This would actually be sensible for a debugging
implementation. ) In any case, there's no point in trying to refer the
value of a pointer after a call to free(); an attempt to do so
probably indicates a bug in the code.
even comparing g to another pointer value invokes undefined behavior.


Even if *g has not been free'd.


No, if free(g) hasn't been called, g can safely be compared for
equality to other pointer values. Some comparisons with <, <=, >, and= do invoke undefined behavior; perhaps that's what you were thinking of.
Of course, undefined behavior is a tricky thing;
it can, and often does, manifest itself
as the program doing exactly what you think it should.


No. Undefined behavior
is simply behavior not defined by the ANSI/ISO C [89]9 standard.
The behavior may be defined by the implementation,
the computer architecture, the operating system or some other standard.


And how does that contradict what I said? In any case, many instances
of undefined behavior are *not* defined by any other standard.
(Murphy's law, which is outside the scope of the C standard,
implies that it will then stop working
at the most inconvenient possible moment.)


Not if the behavior is defined
by something besides the ANSI/ISO C [89]9 standard.


You do know that Murphy's law is a joke, right?
C is used to write platform specific applications such as
device drivers, operating system kernels and standard C libraries.
It is neither practical or desirable to comply
with the ANSI/ISO C standards in such applications.
It is both practical and desirable to comply with the ISO standard as
much as possible (but no more than possible). It is neither practical
nor desirable to discuss the details of any platform-specific code in
this newsgroup; the people who can discuss it intelligently hang out
in platform-specific newsgroups.
After you've called free(g), you can assign a new value to g:
g = malloc(sizeof *g);
... /* g is now valid */
free(g);
... /* g is now invalid */
g = malloc(sizeof *g);
... /* g is now valid again */


But you said, "Also, any reference to g, the pointer variable,
invokes undefined behavior, even if you don't dereference it."


Yes. Perhaps I should have said any reference to the value of g.
Doesn't

g = malloc(sizeof *g);

reference g?


No. The operand of the sizeof operator is not evaluated (unless the
operand is a C99 variable length array, but that doesn't apply here).
The assignment doesn't refer to the value of g, it simply assigns a
new value.
This is allowed because it assigns a new value to g
without referring to the previous value.


That's not the same thing as "referencin g g".


What's not the same thing? I can't tell whether you're agreeing or
disagreeing with me. By "referencin g g", I mean "referring to (or
using) the value of g".
C and C++ are two different languages, and we really can't discuss
C++ here in comp.lang.c.


That's your opinion. You're welcome to it.
But I don't share it.


I presume you're referring to the second part of my statement; you
agree that C and C++ are two different languages, don't you?

Is it your opinion that the existing C++ newsgroups should be
abolished, and both languages should be discussed in the C newsgroups?
You're free to advocate that, but I don't think you'll have much luck.
If you want to discuss C++,
feel free to do so in one of the C++ newsgroups.


That's religious intolerance. I don't share your bigotry.
If you don't want to discuss C++, please ignore all references to C++.
Just snip them out of your replies.


Nonsense. If I don't want to discuss C++, I won't read the C++
newsgroups. If I do, I will. The consensus against discussing C++ in
comp.lang.c isn't about any dislike of the C++ language; for the most
part, it's because the regulars of comp.lang.c aren't able to provide
knowledgeable answers to questions about C++, or to correct errors in
other people's postings. That's *exactly* what comp.lang.c++ is for.

To the original poster (if you haven't given up by now): your original
question was about the new and delete operators, which are specific to
C++ and do not exist in C. You were advised to post your question in
comp.lang.c++, not because we were trying to get rid of you, but
because that's where to find the people who are able to answer
questions about new and delete. When you posted a revised question
about malloc() and free(), that was perfectly appropriate for
comp.lang.c, but it was a different question. malloc() and free() are
similar to new and delete, but they're not the same thing -- and I,
for one, am not competent to explain in detail what the differences
are. (If you're curious, comp.lang.c++ would be a good place to ask
about it, since C++ includes the C standard lirary. Be sure to check
the C++ FAQ first; it might already answer any questions you have.)

Some of us may seem abrupt at times (and sometimes some of us can be
downright rude) but for the most part we're sincerely trying to be
helpful -- even (or especially) when we advise you to go somewhere
else.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #18
Hi, I am still here :-)
Although the call to free() isn't going to change the bits
that make up the value of g, It can't. g is passed by value.

Right.


g is passed by value to free( ) and this is why it continues to have the
same value -pointing to the same memory location- after free( ) is called (I
hope I ve got it right). What may cause the pointer to assume an
indeterminate value?

free(g);
g = malloc(sizeof *g);

No. The operand of the sizeof operator is not evaluated (unless the
operand is a C99 variable length array, but that doesn't apply here).
The assignment doesn't refer to the value of g, it simply assigns a
new value.


I still cant understand this :-(

You said: "After the call to free(g) any reference to *g invokes undefined
behavior". I would have thought that as sizeof *g refers to/uses *g it may
invoke an undefined behavior. You said that the operator is not evaluated.
Can you elaborate please?

I presume you're referring to the second part of my statement; you
agree that C and C++ are two different languages, don't you?
If there was a standardised code of conduct for use in the comp.lang.c, it
would have definitely describe this as an inappropriate behaviour
(and who am I to judge you,e?)

To the original poster (if you haven't given up by now): your original
question was about the new and delete operators, which are specific to
C++ and do not exist in C.
This is true :-). I clicked on the wrong newsgroup.

However Robert was kind enough to convert my code in C and answer my
question in terms of C in which I am also interested in. I was wondering how
is it possible to free( ), dereference the pointer and still access the data
which I had assigned before. His example answered exactly this. Then Keith
told me that I should not refer to or dereference a pointer; it may cause an
undefined behaviour. The bottom line is that may and I have learned a lot -
which is the whole point of newsgroups- even though I posted my question to
the wrong newsgroup. There is no need for people to get upset and be rude.
This is what Robert wants to communicate.

I should also add that there are many like Robert in newsgroups. I have
seen questions that should have been posted to different newsgroup being
answered by people that happened to know the answer. I have also seen
questions that should have been posted to different newsgroup just being
ignored. I have also seen polite answers pointing out where one should ask
in order to find an answer to his/her question. I have also seen sarcastic,
inappropriate rude answers by people that consider themselves the
"fathers/guardians" of a new newsgroup. An answer reflects the quality of
ones character.
Some of us may seem abrupt at times (and sometimes some of us can be

downright rude)

There is no reason to be rude in newsgroups or even get upset by some
posts. The whole idea is openess, sharing of ideas, providing help,
co-operation, companionship.. ....if one gets upset by some posts s/he may
consider to stop providing his/hers services to the newsgroup as there will
always be people just like myself that will unintetionaly post questions to
the wrong place and get them upset.

Nov 14 '05 #19
Keith Thompson wrote:
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
Keith Thompson wrote:

.... snip ...
If you want to discuss C++,
feel free to do so in one of the C++ newsgroups.
That's religious intolerance. I don't share your bigotry.
If you don't want to discuss C++, please ignore all references
to C++. Just snip them out of your replies.


Nonsense. If I don't want to discuss C++, I won't read the C++
newsgroups. If I do, I will. The consensus against discussing
C++ in comp.lang.c isn't about any dislike of the C++ language;
for the most part, it's because the regulars of comp.lang.c aren't
able to provide knowledgeable answers to questions about C++, or
to correct errors in other people's postings. That's *exactly*
what comp.lang.c++ is for.

To the original poster (if you haven't given up by now): your
original question was about the new and delete operators, which
are specific to C++ and do not exist in C. You were advised to
post your question in comp.lang.c++, not because we were trying
to get rid of you, but because that's where to find the people
who are able to answer questions about new and delete. When you

.... snip ...
Some of us may seem abrupt at times (and sometimes some of us can
be downright rude) but for the most part we're sincerely trying
to be helpful -- even (or especially) when we advise you to go
somewhere else.


However ERT, popularly known as Trollsdale, is not one of those
helpful ones. His objective seems to be to impart misinformation,
sometimes subtly, sometimes crudely, and even sometimes interposed
between accuracies. You must never trust anything in his
messages, even if they appear to be quotes from others, because he
has the admirable habit of altering these to suit his
unmentionable taste and objectives.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #20

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

Similar topics

2
9367
by: Eric | last post by:
Hi, I'm used to C/C++ where if you "new" something you really need to "delete" it later. Is that also true in javascript? if i do "mydate = new date();" in a function and dont "delete mydate" when the function exits do i have a memory leak or other trouble brewing? ie: function MyFn() { var mydate;
28
490
by: jimjim | last post by:
Hello, This is a simple question for you all, I guess . int main(){ double *g= new double; *g = 9; delete g; cout<< sizeof(g)<<" "<<sizeof(double)<<" "<<sizeof(*g)<<" "<<*g<<" "<<endl; *g = 111; cout<< sizeof(g)<<" "<<sizeof(double)<<" "<<sizeof(*g)<<" "<<*g<<" "<<endl;
0
9431
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
9255
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
10014
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
9819
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
9689
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...
1
7226
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
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
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.