473,782 Members | 2,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory question


Hi All,

As per the standard what is the result of passing NULL to both malloc and free?

Regards,
Mohan.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05
32 2677

Mohanasundaram wrote:
Hi All,

As per the standard what is the result of passing NULL to both malloc and free?


The rules in the C++ standard for malloc and free are the same as in C.

The malloc function takes an integer argument representing size, not NULL, which
is a null pointer constant.

Assuming you meant malloc(0), the results depend on the implementation. An
implementation is allowed always to return a null pointer, or to return a unique
pointer if it can (it's possible to run out of address space). It cannot return
a pointer to an existing object. Whatever the return, you are not allowed to
dereference the pointer, because it need not point to allocated memory. (You
asked for 0 bytes, after all.)

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.

The short answer is that malloc(0) is allowed, but you can't depend on doing
much with the result. Allowing malloc(0) simplifies some algorithms.

Passing a null pointer to free() is allowed, and has no net effect.

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

--
Steve Clamage, st************* @sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #11

Mohanasundaram wrote:

Hi All,

As per the standard what is the result of passing NULL to both malloc and free?


In C, the behavior of malloc(NULL) depends upon your implementation.
1. NULL can be an integer constant expression with a value of 0, in
which case you've done the eqivalent of calling malloc(0). Per 7.20.3p1
of the C standard:

"If the size of the space requested is zero, the behavior is
implementation defined: either a null pointer is returned, or the
behavior is as if the size were some nonzero value, except that the
returned pointer shall not be used to access an object."

2. NULL can be an integer constant expression with a value of 0, cast to
void* (this is not permitted in C++). In that case, malloc(NULL) is
equivalent to malloc((void*)0 ), which in turn is equivalent to
malloc((size_t) (void*)0). The result of (size_t)(void*) 0 is
implementation-defined; it can be any valid size_t value. On a great
many implementations , it will be 0, but there are real implementations
where it might not be, and portable code should not count on that.

free(NULL) is much simpler. Per 7.20.3.2p2 of the C standard: "If ptr is
a null pointer, no action occurs.".

The C++ standard incorporates by reference most of the C standard
library's description. The only changes it makes are to specify that
malloc() does not call ::operator new(), and free() does not call
::operator delete().

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #12
Joe Wright <jo********@ear thlink.net> wrote in message news:<40******* ****@earthlink. net>...
Peter Pichler wrote:

"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:8b******** *************** *********@4ax.c om...
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@ msn.com
(Mohanasundaram ) wrote:
.... The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.

May or may not? NULL is 0 or ((void *)0) and because of C89 prototyping
will arrive at malloc as 'size_t 0' graranteed. What 'compilation error'
were you thinking about?

How do you arrive at 'size_t 0'? The conversion is not implicit -
arguments to function calls are converted according to the same rules
as assignment, and pointer->integer type isn't one of the options
allowed by the constraints on assignment.

However, even if the conversion could occur implicitly, there's
nothing in the standard that guarantees that (size_t)(void*) i == i for
any integer, not even case where 'i' is replaced by a literal '0'.
Nov 14 '05 #13

Steve Clamage <St************ *@Sun.COM> wrote in message news:<c0******* ***@news1nwk.SF bay.Sun.COM>...

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?

Dylan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #14

In comp.std.c Steve Clamage <St************ *@sun.com> wrote:

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.


C99 7.20.3:

If the size of the space requested is zero, the behavior is
implementation-defined: either a null pointer is returned, or
the behavior is as if the size were some nonzero value, except
that the returned pointer shall not be used to access an object.

C90 contained slightly different language that was more easily misread,
but the intent was the same.

-Larry Jones

It's either spectacular, unbelievable success, or crushing, hopeless
defeat! There is no middle ground! -- Calvin
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #15

On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), la************@ ugsplm.com
wrote:

In comp.std.c Steve Clamage <St************ *@sun.com> wrote:

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.


C99 7.20.3:

If the size of the space requested is zero, the behavior is
implementation-defined: either a null pointer is returned, or
the behavior is as if the size were some nonzero value, except
that the returned pointer shall not be used to access an object.

C90 contained slightly different language that was more easily misread,
but the intent was the same.


Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.

Suppose the malloc/free implementation reserves one byte, malloc(0)
always returns the address of that byte, and free() of that address is
a no-op. I don't see any rule violation.
---
Steve Clamage, st************* @sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #16

On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), wi******@hotmai l.com (Dylan
Nicholson) wrote:

Steve Clamage <St************ *@Sun.COM> wrote in message news:<c0******* ***@news1nwk.SF bay.Sun.COM>...

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?


Bear in mind the following differences:

A new-expression like
new T // T is some type
new T[size}
is a syntactical construct that causes memory to be allocated by the
memory allocation function associated with type T, followed by
contructor invocation(s) for the allocated object(s).

The C++ standard library contiains six different overloads of operator
new, a function that can be called explicitly to allocate raw memory.
You can also write your own overloads, and replace some of the default
versions. The rules are given in the C++ standard section 18.4.1 and
3.7.3. A new-expression invokes some version of operator new, as
explained in section 5.3.4.

C++ also inherits library functions malloc and free from C, which can
be called explicitly to manage raw storage. The C++ standard does not
require that malloc (or free) be used in the implementation of new (or
delete) expressions, or of operator new (or operator delete).

The code you show involves a new-expression and a delete-expression,
not direct calls to malloc or free.

I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size. But
I tried a couple of compilers at full warning levels, and neither
complained about new char[0].

If the code is invalid, the standard imposes no requirements on the
behavior of the program. But it seems to me that an implemention
allowing the expression should also allow deleteing the pointer that
was returned.

Calling the operator new function explicitly is a different story,
however. The expression
operator new(0)
is valid. If the operation succeeds, it must return a unique address
for each call, which can be passed to the corresponding operator
delete().
---
Steve Clamage, st************* @sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #17

wi******@hotmai l.com (Dylan Nicholson) writes:
Steve Clamage <St************ *@Sun.COM> wrote in message
news:<c0******* ***@news1nwk.SF bay.Sun.COM>...
> The net result of these rules is that you can always call free
> (once) with the result you got from malloc.
>

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?


I'm posting in comp.std.c. From that point of view, I'm not sure
whether crashing (at run-time?) on a syntax error is non-compliant.
As long as it generates a diagnostic during compilation, it's probably
all right.

As far as C++ is concerned, I don't know whether the delete []
operator follows the same rules as free(). I've redirected followups
to comp.lang.c++.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #18

James Kuyper <ku****@saicmod is.com> wrote in message
news:<40******* ********@saicmo dis.com>...
2. NULL can be an integer constant expression with a value of 0, cast
to void* (this is not permitted in C++). In that case, malloc(NULL) is
equivalent to malloc((void*)0 ), which in turn is equivalent to
malloc((size_t) (void*)0). The result of (size_t)(void*) 0 is
implementation-defined; it can be any valid size_t value. On a great
many implementations , it will be 0, but there are real implementations
where it might not be, and portable code should not count on that.
However, the conversion of ((void*)0) to an integral type requires an
explicit cast. If this is the definition of NULL, then malloc(NULL)
should not compile.
free(NULL) is much simpler. Per 7.20.3.2p2 of the C standard: "If ptr
is a null pointer, no action occurs.". The C++ standard incorporates by reference most of the C standard
library's description. The only changes it makes are to specify that
malloc() does not call ::operator new(), and free() does not call
::operator delete().


Yes, but the removal of the liberty to define NULL as ((void*)0) means
that in C++, malloc(NULL) is always legal, where as in C, there are
implementations where it may fail.

--
James Kanze GABI Software mailto:ka***@ga bi-soft.fr
Conseils en informatique orientée objet/ http://www.gabi-soft.fr
Beratung in objektorientier ter Datenverarbeitu ng
11 rue de Rambouillet, 78460 Chevreuse, France, +33 (0)1 30 23 45 16
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #19

On Mon, 9 Feb 2004 03:26:12 +0000 (UTC), Stephen Clamage
<St************ *@Sun.COM> wrote:
I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size. But
I tried a couple of compilers at full warning levels, and neither
complained about new char[0].


Maybe another read would help. T[0] contains an expression which must
be non-negative. The expression happens but is not required to be
constant. T[0][5] is a form which requires the second expression to
be constant and positive. Does that make sense?

John
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #20

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

Similar topics

32
3865
by: John | last post by:
Hi all: When I run my code, I find that the memory that the code uses keeps increasing. I have a PC with 2G RAM running Debian linux. The code consumes 1.5G memory by the time it finishes execution. But I do not think it needs so much memory. About 500M memory should be enough. I have following questions about memory leak. (1).If in my code I only define constructor for my class, and do not define destructor, will it cause memory leak?
6
2702
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the memory allocation algorithm, but for gathering some statistics and to find memory leaks.) This seems to work. However, I noticed that my replacing delete operator is not called
20
3068
by: Jonas | last post by:
Hi, I'm 99 % sure that Standard C guarantees to do a memory move inside realloc() in case the new, returned memory block (address) is different than the original one. Can any C expert confirm this to me, please? Thanks, Jonas PS. I using C90, not C99--if it makes a difference.
8
2934
by: vikram | last post by:
i have series of questions 1.How a c program is loaded in memory i mean the whats is the structure that the code segment?? data segment?? 2.When you say const int *p; where is p stored in the memory?? what happens internal so that its a read only. 3. when declared volatile int *p where exactly in the memory it is stored.
30
3751
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;
18
2273
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
25
2388
by: Zeng | last post by:
I finally narrowed down my code to this situation, quite a few (not all) of my CMyClass objects got hold up after each run of this function via the simple webpage that shows NumberEd editbox. My memory profile shows that those instances survive 3 rounds of GC collections - it's not what I expected. In my real code, CMyClass occupies big amount of memory and they all share one stance of another class that I don't have enough memory hold...
2
1374
by: Ashish | last post by:
hi all, I have been doing some performance testing of a asp_net website, to be hosted on a shared server .. as far as i understand every page when accessed first time is compiled and loaded in the memory of aspnet_wp , so that would mean more distinct pages more the memory consumed by aspnet_wp, this is good since it would mean serving compiled copy of the page , which is good for speed.. another understanding is that once a page is...
7
4693
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now are the memory layout is contiguous? i.e all the character resides side by side just like array, and all Points side by side insede the
9
4538
by: Hemal | last post by:
Hi All, I need to know the memory required by a c program. Is there any tool/utility which can give me the memory usage in terms of DATA segment, TEXT segment, BSS segment etc. I am working on linux platform and my target is ARM processor. But i guess it should not matter. Actually i need to know both RAM & ROM usage.
0
9480
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
10313
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
9944
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
8968
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
7494
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
6735
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();...
0
5378
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.