473,770 Members | 1,862 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

call to malloc with size 0

Neo
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)mallo c(0)) == NULL)

printf("NULL\n" );

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???

-Neo


Nov 14 '05
54 7868
Neo

"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******** *************** *****@netactive .co.uk...
On Wed, 17 Nov 2004 15:49:10 +0530, Ravi Uday wrote:

"Neo" <ti************ ***@yahoo.com> wrote in message
news:30******** *****@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is

the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)mallo c(0)) == NULL)
Get rid of the cast. The compiler should then complain, which is
good because the code is broken. Adding the cast doesn't fix the
code, it just stops the compiler complaining about the problem.

The problem is that you don't have a valid declaration for malloc()
in scope when you call it. In that case the compiler assumes
that malloc() returns int, but it doesn't, it returns void *. All
standard library functions are provided with a declaration in
the appropriate standard header. For malloc() that is <stdlib.h>.

printf("NULL\n" );

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???
Your code invokes undefined behaviour due to the invalid cast, so anything
can happen. Once that's fixed the issue is as below i.e. the compiler does
it because the standard says it can.


invalid cast - what do you mean by saying *invalid cast*. isnt it a standard
practice to cast the pointer returned by the malloc() to desired type? or
how then it can be otherwise like:
p = malloc(0);
???

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !


Lawrence

Nov 14 '05 #11
Neo wrote:
I've a simple qestion related to dynamic memory allocation in C.
[snip]
cat main.c #include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

char *p = (char*)malloc(0 );

if(NULL == p)
printf("NULL\n" );
else
printf("Valid Pointer\n");

printf("*((int* )p - 1) = %d\n", *((int*)p - 1));
printf("p = %p\n", p);
return EXIT_SUCCESS;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main Valid Pointer
*((int*)p - 1) = 17
p = 0x9876008

My implementation allocates at least two
double word aligned double words
and returns a pointer to the second double word.
Why this code fragment returns a valid pointer to a memory block?


Because it can.

Nov 14 '05 #12
Neo wrote:
#include <stdio.h> if( (p=(char*)mallo c(0)) == NULL)
isnt it a standard
practice to cast the pointer returned by the malloc() to desired type?


No.
It's a mistake that people make when they neglect to include stdlib.h,
and the compiler consequently warns them that malloc is returning
type int and needs to be cast.
Add
#include <stdlib.h>
and drop the cast.

--
pete
Nov 14 '05 #13

"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******** *************** *****@netactive .co.uk...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
...
<OT>

Why didn't they put it in the standard that a null pointer must be returned? It seems like the right/logical behaviour for calling malloc on size 0 and avoids any confusion.

</OT>


Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.


Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this magical
pointer.
Nov 14 '05 #14
Neo
Right, thnx. for pointing it out.
its workin perfect!
-Neo

"pete" <pf*****@mindsp ring.com> wrote in message
news:41******** ***@mindspring. com...
Neo wrote:
>>> #include <stdio.h> >>> if( (p=(char*)mallo c(0)) == NULL)

isnt it a standard
practice to cast the pointer returned by the malloc() to desired type?


No.
It's a mistake that people make when they neglect to include stdlib.h,
and the compiler consequently warns them that malloc is returning
type int and needs to be cast.
Add
#include <stdlib.h>
and drop the cast.

--
pete

Nov 14 '05 #15
Method Man <a@b.c> scribbled the following:
"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******** *************** *****@netactive .co.uk...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
> <OT>
>
> Why didn't they put it in the standard that a null pointer must be returned? > It seems like the right/logical behaviour for calling malloc on size 0 and > avoids any confusion.
>
> </OT>
Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.

Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this magical
pointer.


If the C memory model was continuous rather than discrete, then there
would be no problem. In a continuous memory model, pointer values would
only serve as "starting points" of allocated memory, not allocated
memory itself. If you think of the conventional discrete memory model as
labelling boxes with addresses, in a continuous memory model you don't
label the boxes, you label the gaps between them. This way the malloc()
implementation could safely return the same, non-null, pointer value
over and over again from calls to malloc(0), because reserving 0 bytes
onward from that gap between boxes doesn't actually reserve any box at
all, and it's the boxes you store stuff in, not the gaps between them.
This is of course very much off-topic for comp.lang.c but those who
have studied real analysis and topology know what I'm talking about.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"It's time, it's time, it's time to dump the slime!"
- Dr. Dante
Nov 14 '05 #16
In <5g************ ******@read1.cg ocable.net> "Method Man" <a@b.c> writes:

"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******* *************** ******@netactiv e.co.uk...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
...
> <OT>
>
> Why didn't they put it in the standard that a null pointer must bereturned? > It seems like the right/logical behaviour for calling malloc on size 0and > avoids any confusion.
>
> </OT>
Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.


Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0).


It's a "cheap" method for generating unique IDs.
I would be curious to know how the
implementati on handled dereferencing and type-casting for this magical
pointer.


The pointer is as ordinary as you can get. Dereferencing it invokes
undefined behaviour and conversions work as for other pointers. As
Lawrence told you, if you need this particular behaviour, just use the
following wrapper for malloc:

void *xmalloc(size_t size)
{
if (size == 0) size = 1;
return malloc(size);
}

And if you need the other behaviour, you can trivially get it from:

void *ymalloc(size_t size)
{
if (size == 0) return NULL;
return malloc(size);
}

Or, if you prefer macros:

#define XMALLOC(size) malloc(size == 0 ? 1 : size)
#define YMALLOC(size) (size == 0 ? NULL : malloc(size))

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #17

"Dan Pop" <Da*****@cern.c h> wrote in message
news:cn******** **@sunnews.cern .ch...
In <5g************ ******@read1.cg ocable.net> "Method Man" <a@b.c> writes:
Fair enough. Although, I can't immediately see a practical use in
obtaining
a valid pointer from malloc(0).


It's a "cheap" method for generating unique IDs.


Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0? It might have to increment a reference count that would
later get decremented by free().
Nov 14 '05 #18
"Craig Barkhouse" <ca******@stude nt.cs.uwaterloo .ca> wrote:
Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0?


In C89, it isn't perfectly clear; the text says that

# If the space cannot be allocated, a null pointer is returned.
# If the size of the space requested is zero, the behavior is
# implementation-defined; the value returned shall be either a null
# pointer or a unique pointer.

without clarifying whether that means a pointer unique to zero-sized
malloc()s, or a unique pointer for _each_ zero-sized malloc().

In C99, this has been changed to

# 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.

Since

# Each such allocation shall yield a pointer to an object disjoint from
# any other object.

this means that in C99, each zero-sized malloc() must return a distinct
pointer (or a null pointer), and I think that with this knowledge, it's
clear that this was what was meant in C89, too.

Richard
Nov 14 '05 #19
"Method Man" <a@b.c> writes:
I can't immediately see a practical use in obtaining a valid
pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this
magical pointer.


Dereferencing the result of malloc(0) yields undefined behavior.
What problem do you envision with type-casting it?
--
"The way I see it, an intelligent person who disagrees with me is
probably the most important person I'll interact with on any given
day."
--Billy Chambless
Nov 14 '05 #20

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

Similar topics

13
83901
by: mike79 | last post by:
hi all.. if I wanted to malloc a struct, say the following: struct myStruct1 { int number; char *string; }
10
2318
by: pembed2003 | last post by:
Hi, If I have the folllowing: char* p = malloc(5); memset(p,-1,5); *p = 0; printf("%d\n",strlen(p)); free(p); It will print 0. Is there a way to retrive the initial size of memory
7
2216
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
42
2180
by: Joris Adriaenssens | last post by:
This is my first posting, please excuse me if it is off-topic. I'm learning to program in C. It's been almost ten years I've been programming and a lot of things have changed apparently. I understand from other postings that casting a result from malloc isn't good. In the past I have always been casting the malloc. I think it was even necessary. (But that's a long time ago, I hadn't heard of a standard for C these days). Was it...
14
3297
by: Marlene Stebbins | last post by:
At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write: if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_x))) == NULL) { exit(EXIT_FAILURE); fprintf(stderr, "malloc failed"); } for each individual call if there is a stylistically better way. How
3
11445
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to write a code to do like a dynamic array, and the code is as
18
3318
by: cs | last post by:
This is the function malloc_m() that should be like malloc() but it should find memory leak, and over bound writing in arrays. How many errors do you see? Thank you ******************************************** /* mallocm.c */ /* funzione di libreria per trattamento della memoria e rilevamento errori */ /* uso: c_compiler malloc.c e usare malloc .obj */
3
1437
by: melanieab | last post by:
Hi, I'm having trouble when I leave a tabpage to go on to the next. On Focus Leave, I take a snapshot of that tab. It usually turns out ok, but often, part of the next tabpage will appear in this snapshot (an outline of a picturebox or textbox). Is there anything I can do about this? Thanks!!!! Mel
71
19131
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
0
9617
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
9454
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
10099
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
9904
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
7456
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
6710
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
5354
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...
1
4007
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
3
2849
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.