473,791 Members | 2,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloced union member

Hi,

Iam confused as to when is the memory freed in this program.

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

union test{
char *i;
char *ch;
};

int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.i);
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.ch);
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);

return 0;
}

And the output I get from my solaris box is :
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]

regards
rohitash
Nov 14 '05 #1
10 1349
pr******@yahoo. com (rohit) wrote:
Iam confused as to when is the memory freed in this program.

union test{
char *i;
char *ch;
};

int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.i);
It is free()d here...
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
....so this statement invokes undefined behaviour.
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]


Yes, appearing to work as "normal" is one of the legal results of
undefined behaviour. Should you now be tempted to abuse this feature,
beware! Appearing to work as normal on your testing machines but
crashing spectacularly on your customer's network is _also_ a legal
result of UB...

Richard
Nov 14 '05 #2
rohit wrote:

Hi,

Iam confused as to when is the memory freed in this program.

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

union test{
char *i;
char *ch;
};

int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.i);
Why are you `free()'ing "test.i" here?
You allocated the memory to "test.ch"
(even though both elements of the union
happen to contain the same pointer value,
that's a very bad practice).
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.ch);
You got lucky here. You've `free()'d the same
pointer value _twice_. You've corrupted your heap.
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);

return 0;
}

And the output I get from my solaris box is :
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]

regards
rohitash


It looks like you're expecting the call to `free()'
to somehow change the contents of the object the
pointer was pointing to, or even the pointer itself.
The value of a pointer after a call to `free()'
is indeterminate.

In this particular case, you were able to dereference
the pointer and it still contained your original
value. This is dumb luck.

To answer your question, the memory obtained by
a call to `malloc()' is "free" at the point of entry
into the call to `free()'. "free" is a non-specific
term, however, and should be taken to mean that it
is not "free" for your program to access any longer.
Some architectues may generate an error accessing
the memory through that pointer, some may do nothing,
and some may give the _appearence_ that the memory
is still valid and contains valid data (as on your
Solaris box).
HTH,

Stephen
Nov 14 '05 #3
"Stephen L." <sd*********@ca st-com.net> wrote:
rohit wrote:
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.ch);


You got lucky here. You've `free()'d the same
pointer value _twice_. You've corrupted your heap.


You don't know this. It invokes undefined behaviour; this _may_ mean
corrupting his heap, but it may also mean ignoring the statement,
crashing with a segmentation fault, or mailing his resume to
bi******@whiteh ouse.gov.

Richard
Nov 14 '05 #4
Richard Bos wrote:

"Stephen L." <sd*********@ca st-com.net> wrote:
rohit wrote:
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.ch);


You got lucky here. You've `free()'d the same
pointer value _twice_. You've corrupted your heap.


You don't know this. It invokes undefined behaviour; this _may_ mean
corrupting his heap, but it may also mean ignoring the statement,
crashing with a segmentation fault, or mailing his resume to ...

Richard


man malloc(3c) for details.

Posters who have identified this behavioral
aspect of `free()' have usually noted it by stating
that their (next) `malloc()'/`free()' core dumps.

The second call to `free()' with the same pointer
value as before qualifies as a "random" value.

"Undefined results will occur if the space assigned by
malloc() is overrun or if some random number is
passed to free()."

-Solaris 8 man page

It _doesn't_ say, "and BTW, the heap is fine."
A reasonable and valid conclusion based on the facts
as presented in the man page (along with other sources)
is that the heap, after a `free()'ing the same
pointer twice, is not usable, even if `free()'
seemed to return okay. I see nothing in the man
page(s) which would bring me to any of the
conclusions you've arrived at - why are posters
trying to DEFINE undefined behavior?

I think it's important to try to answer the OP's
question at the level (not in a condescending manner)
that it is asked. The OP didn't say he was using
any special implementation of `malloc()' (there
are versions out there that perform allocation
using much more sophisticated rules and memory models),
so it was reasonable to assume he was using the
"standard malloc-from-the-heap implementation" .
If I was wrong, I'd expect the OP to repost
with a clarification - that's how the dialog
should continue.

But providing garbage answers like "mailing his
resume to ..." really hurt the credibility of
the group as a whole, IMHO.
Stephen
Nov 14 '05 #5
In <40************ **@news.individ ual.net> rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
pr******@yahoo .com (rohit) wrote:
Iam confused as to when is the memory freed in this program.

union test{
char *i;
char *ch;
};

int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.i);


It is free()d here...


Nope, this call merely invokes undefined behaviour.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #6
In <93************ **************@ posting.google. com> pr******@yahoo. com (rohit) writes:
Iam confused as to when is the memory freed in this program.
What else could you expect from a bogus program?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

union test{
char *i;
char *ch;
};
What is the point of this union?
int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
Undefined behaviour: you can't evaluate test.i after initialising test.ch
as they have incompatible types that can't be aliased.
free(test.i);
Undefined behaviour, for the same reason as above.
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
Undefined behaviour.
free(test.ch);
Undefined behaviour. This call would have been correct as the *first*
free call. Now, it is too late...
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
Undefined behaviour.
return 0;
}

And the output I get from my solaris box is :
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]


There is no way to get any enlightment from the output of a meaningless
program. Instead of wasting your time writing and executing junk code,
read the FAQ!

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #7
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Dan Pop wrote:
| In <93************ **************@ posting.google. com> pr******@yahoo. com
(rohit) writes:
|
|
|>Iam confused as to when is the memory freed in this program.
|
|
| What else could you expect from a bogus program?
|
|
|>#include <stdlib.h>
|>#include <stdio.h>
|>#include <string.h>
|>
|>union test{
|> char *i;
|> char *ch;
|>};
|
|
| What is the point of this union?
|
|
|>int main()
|>{
|> union test test;
|> test.ch = malloc(6);
|> strcpy(test.ch, "hello");
|> printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
|>[%p]\n",test.i,test .ch,test.i,test .ch);
|
|
| Undefined behaviour: you can't evaluate test.i after initialising test.ch
| as they have incompatible types that can't be aliased.

Dan, I'm confused.

Given the OP's union, I don't understand how test.i and test.ch can have
"incompatab le types that can't be aliased".

AFAICT, test.i is a pointer to char, and test.ch is a pointer to char. To me,
those don't look like "incompatab le types".

Did I read something wrong? Could you clear up my misunderstandin g?

[snip]

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFArBfkagV FX4UWr64RAsM8AJ 4gHH989fW30y+lO cUSGEJEULytjgCe NOQ8
8O8w2bmyTSUPcpD 6qVJYaAk=
=u+rD
-----END PGP SIGNATURE-----
Nov 14 '05 #8


rohit wrote:
Hi,

Iam confused as to when is the memory freed in this program.

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

union test{
char *i;
char *ch;
};

int main()
{
union test test;
test.ch = malloc(6);
strcpy(test.ch, "hello");
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.i);
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);
free(test.ch);
printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
[%p]\n",test.i,test .ch,test.i,test .ch);

return 0;
}

And the output I get from my solaris box is :
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]
test.i == hello test.ch == hello test.i == [209b8] test.ch == [209b8]

regards
rohitash


The memory is "freed" when you call free(). free() lets the system know
that the memory is not used. It does not have to erase it. So you can
still look at it (on you system). But other systems may not let you look
at memory you do not own. freeing memory you do not own is never good.
it is a good idea to set you pointers to NULL after free() you can then
check them for NULL to insure you do not use pointers that no loner
pointing to memory you own.
Nov 14 '05 #9
In <lJ************ ********@news20 .bellglobal.com > Lew Pitcher <lp******@sympa tico.ca> writes:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Dan Pop wrote:
| In <93************ **************@ posting.google. com> pr******@yahoo. com
(rohit) writes:
|
|
|>Iam confused as to when is the memory freed in this program.
|
|
| What else could you expect from a bogus program?
|
|
|>#include <stdlib.h>
|>#include <stdio.h>
|>#include <string.h>
|>
|>union test{
|> char *i;
|> char *ch;
|>};
|
|
| What is the point of this union?
|
|
|>int main()
|>{
|> union test test;
|> test.ch = malloc(6);
|> strcpy(test.ch, "hello");
|> printf("test.i == %s test.ch == %s test.i == [%p] test.ch ==
|>[%p]\n",test.i,test .ch,test.i,test .ch);
|
|
| Undefined behaviour: you can't evaluate test.i after initialising test.ch
| as they have incompatible types that can't be aliased.

Dan, I'm confused.

Given the OP's union, I don't understand how test.i and test.ch can have
"incompatabl e types that can't be aliased".

AFAICT, test.i is a pointer to char, and test.ch is a pointer to char. To me,
those don't look like "incompatab le types".

Did I read something wrong? Could you clear up my misunderstandin g?


My mistake, I interpreted test.ch as having the type pointer to char and
test.i pointer to int, despite the fact that I have actually looked at the
union definition....

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #10

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

Similar topics

5
8150
by: Simon Elliott | last post by:
I'd like to do something along these lines: struct foo { int i1_; int i2_; }; struct bar {
6
3335
by: Neil Zanella | last post by:
Hello, I would like to know what the C standards (and in particular the C99 standard) have to say about union initializers with regards to the following code snippet (which compiles fine under gcc 3.2.2 but does not produce the expected results, the expected results being the ones annotated in the comments in the code): #include <stdlib.h>
18
2381
by: ranjeet.gupta | last post by:
Dear ALL As we know that when we declare the union then we have the size of the union which is the size of the highest data type as in the below case the size should be 4 (For my case and compiler), and it is, what I conclude from the below code union data_type {
16
2110
by: tedu | last post by:
does anyone know of a platform/compiler which will place union elements to not overlap? as in union u { int a; long b; size_t c; }; in my limited experience, writing to any of (a, b, or c) will affect the value read from any other. i understand this is UB, but i'm
8
5664
by: wkaras | last post by:
In my compiler, the following code generates an error: union U { int i; double d; }; U u; int *ip = &u.i; U *up = static_cast<U *>(ip); // error I have to change the cast to reinterpret_cast for the code
30
3284
by: Yevgen Muntyan | last post by:
Hey, Why is it legal to do union U {unsigned char u; int a;}; union U u; u.a = 1; u.u; I tried to find it in the standard, but I only found that
32
1863
by: =?gb2312?B?zfWzrLey?= | last post by:
Union un { int I; char c; } main() { union un x; x.c=10; x.c=1;
7
6422
by: Peter Olcott | last post by:
Why can a union have a member with a copy constructor?
3
7726
by: SRK | last post by:
Hi, I wanted to use an anonymous union within an structure something like below - struct Test { union { std::string user; //char user; std::string role; //char role;
0
10427
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
10207
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
9995
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
7537
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
5431
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
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.