Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > How to check whether malloc has allocated memory properly in case ifmalloc(0) can return valid pointer

Reply
Thread Tools

How to check whether malloc has allocated memory properly in case ifmalloc(0) can return valid pointer

 
 
Eric Sosman
Guest
Posts: n/a
 
      12-16-2010
On 12/16/2010 10:54 AM, Ered China Luin wrote:
> In article<iedbs0$7i8$>,
> "Joachim Schmitz"<> wrote:
>
>> Shivanand Kadwadkar wrote:

>
> Since I have up to 50 gigabytes of memory available, I don't bother checking.
> I'mh appy risking an abort on memory address.
>
>>> i want to check after calling malloc whether allocation is successful
>>> or not. previously i have done like
>>>
>>> ptr=malloc(size);
>>>
>>> if(ptr==NULL)
>>>
>>> But i came to know malloc can return valid pointer in case if argument
>>> is zero.
>>>
>>> one solution is
>>>
>>> if(size==0)
>>> ptr=NULL;
>>> else
>>> ptr=malloc(size);
>>>
>>> if you have any other suggestion please welcome.

>
> (1) Decide exactly what you want malloc to return under all possible conditions.
>
> (2) Write your own allocator in front of malloc. Perhaps something like
>
> static char empty = 0;
> void *allocate(int n) {return n==0 ?&empty : malloc(n);}
> void dispose(void *p) {if (p!=&empty) free(p);}


You can do this in your own program if you like, but note that
malloc(0) itself cannot work this way. If it returns non-NULL, it
must return a value that is distinct from all the other values it
has returned (that have not yet been released). That is, malloc(0)
must satisfy:

void *p = malloc(0);
void *q = malloc(0);
assert (p == NULL || p != q);

Of course, you can make your wrapper behave as you please -- but
you can't change the behavior of the underlying malloc().

--
Eric Sosman
lid
 
Reply With Quote
 
 
 
 
Eric Sosman
Guest
Posts: n/a
 
      12-16-2010
On 12/16/2010 11:04 AM, Ered China Luin wrote:
> [...]
> The current interface means you don't have to special case zero. You can
> allocate and process n bytes for n==0 as well n>0 with the same code. For example
>
> ptr p = memcpy(malloc(n), src, n);


Careful! This has undefined behavior if malloc(n) returns NULL,
even if n is zero. See 7.21.1p2 and 7.1.4p1, and note the absence of
any "explicitly stated otherwise" language in 7.21.2.1.

In other words: You needn't special-case zero (much), but you
still need the NULL test.

> This is similar to the old zero trip loops of Fortran and Algol; both languages
> could implement identical semantics, but which had the more of convenient syntax
> was a matter of taste.


In the long-ago days when I used FORTRAN (II and IV), it had
no construct I'd have described as a "zero-trip loop." Specifically,
a DO loop always executed its body at least once.

--
Eric Sosman
lid
 
Reply With Quote
 
 
 
 
Joachim Schmitz
Guest
Posts: n/a
 
      12-16-2010
Tom St Denis wrote:
> On Dec 16, 10:39 am, "Joachim Schmitz" <nospam.j...@schmitz-
> digital.de> wrote:
>> Shivanand Kadwadkar wrote:
>>> i want to check after calling malloc whether allocation is
>>> successful or not. previously i have done like

>>
>>> ptr=malloc(size);

>>
>>> if(ptr==NULL)

>>
>>> But i came to know malloc can return valid pointer in case if
>>> argument is zero.

>>
>>> one solution is

>>
>>> if(size==0)
>>> ptr=NULL;
>>> else
>>> ptr=malloc(size);

>>
>>> if you have any other suggestion please welcome.

>>
>> IMHO the case when malloc(0) return NULL is more interesting, as
>> there you need to adjust the error checking, i.e. not exit the
>> program due to lack of memory if size was 0.

>
> Agreed, I can't ever think of a legit use for malloc'ing zero bytes.
> It should return a NULL to trip up [what should be in place] normal
> error detection.


That is not my point. Of course malloc(0) is stupid, but calculating the
size of a buffer and then malloc()'ing that is legel, even of the size
calculation mey result in 0. But in that case chacking malloc() for
returning NULL is not sufficient for aborting the program, you'd also need
to check size, either before the malloc (and skip it) or after, but befor
jumping to the error handling.

I once had to debug a program, actually 'nm', which aborted with a memory
error on an objectfile, that, as it turned out later, had 0 symbols (which
is not usual, but legal), and so 'nm' successfully malloc()'ed 0 bytes, but
chocked on the NULL check.

Bye, Jojo

 
Reply With Quote
 
Gerald Breuer
Guest
Posts: n/a
 
      12-16-2010
As a memory-block with sizer 0 isn't touched
you don't need to care for this case explicitly.
 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      12-16-2010
On 12/16/2010 11:38 AM, Ered China Luin wrote:
> In article<iedert$6f8$>,
> Eric Sosman<> wrote:
>
>> On 12/16/2010 10:54 AM, Ered China Luin wrote:
>>> [...]
>>> (2) Write your own allocator in front of malloc. Perhaps something like
>>>
>>> static char empty = 0;
>>> void *allocate(int n) {return n==0 ?&empty : malloc(n);}
>>> void dispose(void *p) {if (p!=&empty) free(p);}

>>
>> You can do this in your own program if you like, but note that
>> malloc(0) itself cannot work this way. If it returns non-NULL, it
>> must return a value that is distinct from all the other values it

>
> And you can change it to
> void *allocate(int n) {return malloc(n==0 ? 1 : n);}


That works. It's silly, IMHO, but it works. (Keep in mind that
`int' and `size_t' are not synonymous, so you may be inviting trouble
with your choice of parameter type.)

>> Of course, you can make your wrapper behave as you please -- but
>> you can't change the behavior of the underlying malloc().

>
> And I can hide that malloc if I want.


Not sure what you mean by "hide." You cannot "hide" it in the
sense of making it unavailable to other code in the program, nor can
you "hide" it in the sense of intercepting all malloc() calls and
routing them somewhere other than to the real malloc(). You can, of
course, threaten to flog or "hide" or "give a hiding to" anyone who
calls malloc() directly instead of using your wrapper -- but that's
social engineering, not software engineering.

--
Eric Sosman
lid
 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      12-16-2010
On 12/16/2010 11:52 AM, Ered China Luin wrote:
> In article<iedfgp$3t7$>,
> Eric Sosman<> wrote:
>
>> On 12/16/2010 11:04 AM, Ered China Luin wrote:
>>> [...]
>>> This is similar to the old zero trip loops of Fortran and Algol; [...]

>>
>> In the long-ago days when I used FORTRAN (II and IV), it had
>> no construct I'd have described as a "zero-trip loop." Specifically,
>> a DO loop always executed its body at least once.

>
> I had it very early on.
>
> if (n.eq.0) goto 11
> do 10 i=1,n
> ...
> 10 continue
> 11 continue


The phrase "duck and cover" springs to mind.

That's not a "zero-trip loop," it's an ordinary loop conditionally
skipped. (And it still iterates once for n=-42.) (And it's not "very
early on," because the "logical IF" wasn't in the language prior to
FORTRAN IV.)

--
Eric Sosman
lid
 
Reply With Quote
 
BartC
Guest
Posts: n/a
 
      12-16-2010


"Eric Sosman" <> wrote in message
news:iedo67$d4i$...
> On 12/16/2010 11:52 AM, Ered China Luin wrote:
>> In article<iedfgp$3t7$>,
>> Eric Sosman<> wrote:
>>
>>> On 12/16/2010 11:04 AM, Ered China Luin wrote:
>>>> [...]
>>>> This is similar to the old zero trip loops of Fortran and Algol; [...]
>>>
>>> In the long-ago days when I used FORTRAN (II and IV), it had
>>> no construct I'd have described as a "zero-trip loop." Specifically,
>>> a DO loop always executed its body at least once.

>>
>> I had it very early on.
>>
>> if (n.eq.0) goto 11
>> do 10 i=1,n
>> ...
>> 10 continue
>> 11 continue

>
> The phrase "duck and cover" springs to mind.
>
> That's not a "zero-trip loop," it's an ordinary loop conditionally
> skipped. (And it still iterates once for n=-42.) (And it's not "very
> early on," because the "logical IF" wasn't in the language prior to
> FORTRAN IV.)


Fortran IV came out nearly 50 years ago. How much earlier do you want to go?

--
Bartc

 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      12-17-2010
On 12/16/2010 6:08 PM, BartC wrote:
>
>
> "Eric Sosman" <> wrote in message
> news:iedo67$d4i$...
>> On 12/16/2010 11:52 AM, Ered China Luin wrote:
>>> In article<iedfgp$3t7$>,
>>> Eric Sosman<> wrote:
>>>
>>>> On 12/16/2010 11:04 AM, Ered China Luin wrote:
>>>>> [...]
>>>>> This is similar to the old zero trip loops of Fortran and Algol; [...]
>>>>
>>>> In the long-ago days when I used FORTRAN (II and IV), it had
>>>> no construct I'd have described as a "zero-trip loop." Specifically,
>>>> a DO loop always executed its body at least once.
>>>
>>> I had it very early on.
>>>
>>> if (n.eq.0) goto 11
>>> do 10 i=1,n
>>> ...
>>> 10 continue
>>> 11 continue

>>
>> The phrase "duck and cover" springs to mind.
>>
>> That's not a "zero-trip loop," it's an ordinary loop conditionally
>> skipped. (And it still iterates once for n=-42.) (And it's not "very
>> early on," because the "logical IF" wasn't in the language prior to
>> FORTRAN IV.)

>
> Fortran IV came out nearly 50 years ago. How much earlier do you want to
> go?


"Nearly 50 years ago" FORTRAN IV was available on a handful of
computers. In late 1966 (44 < 50 years ago) I was writing my first
programs in FORTRAN II.

Fortran, with its newfangled mixed-case name (note that even C has
not yet advanced to a mixed-case name), didn't arrive until 1991. By
then, CALL EXIT was a vanished speck in my personal rear-view mirror.

FORTRAN (NO SUFFIX) was altogether before my time, though.

--
Eric Sosman
lid
 
Reply With Quote
 
Ralph Spitzner
Guest
Posts: n/a
 
      12-17-2010
Tom St Denis wrote:
> On Dec 16, 6:38 am, Malcolm McLean<malcolm.mcle...@btinternet.com>


> if (N) {
> employees = calloc(N, sizeof *employees);
> if(!employees) {

break;
//> goto error_handler;
> }
> memcpy(employees, temparray, N * sizeof *employees);
> } else {
> employees = NULL;
> }


if(N && (employees == NULL))
{
do_something_here();
}

>
> There I both fixed the problem and cleaned up your code, that'll be
> 100 shillings please, due net 30.
>
> Tom


only 30 shillings, 70 go for the goto

-rasp

 
Reply With Quote
 
arnuld
Guest
Posts: n/a
 
      12-20-2010
> On Thu, 16 Dec 2010 09:58:40 +0000, BartC wrote:

>> "Mark Bluemel" <> wrote in message
>> And that pointer can successfully be passed to free(). And you are
>> certain to be able to store at least zero bytes at the location pointed
>> to by the pointer, so what's the problem?


> One issue might be that, if you call malloc(0) enough times, you can run
> out of memory!


I tried this and it hanged my system in 60 seconds. Last thing I could
see from top commnd (Linux) after 40 or so seconds that memory usage was
jumping between 83-87% range and CPU u]2sage was 13-17% range and then I
switched to Emacs from urxvt, to look at source code and moved the cursor
10 lines down and then everything just jammed, had to give a hard reboot.

If malloc was called 1000,000 times then memory used still is 0 bytes
(1000,000 * 0 = 0), hence I still wonder when malloc(0) allocates 0 bytes
why system hanged by eating all memory ?



/* **** DO NOT TRY to run this code PLEASE ***. It will crash your
system. */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char* p;

while(1)
{
p = malloc(0);

if(NULL == p)
{
printf("********* Out of Memory ******** \n");
break;
}
}

printf("---------------------\n");

return 0;
}





--
www.lispmachine.wordpress.com
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Re: How to check whether malloc has allocated memory properly in caseif malloc(0) can return valid pointer Gene C Programming 0 12-20-2010 05:33 AM
Dynamically Allocated Memory vs. Statically allocated Memory csnerd@gmail.com C++ 5 12-09-2004 01:44 AM
Malloc/Free - freeing memory allocated by malloc Peter C Programming 34 10-22-2004 10:23 AM
some queries on freeing memory allocated using malloc Hassan Iqbal C Programming 3 09-25-2003 02:53 PM



Advertisments