473,785 Members | 2,297 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 7872
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
Flash Gordon wrote:
Neo wrote:
<snip not casting the return value of malloc.
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);
???
In C, it is standard practice to not cast the value returned by malloc.
Nonsense!


No, it's not nonsense, as we've repeatedly explained at length.
There are a few obscure exceptions, and one person who posts here
has a good reason why he (as opposed to everyone else) has to.


Lots of people who post here have good rerasons
to cast the pointer returned by the malloc(size_t).


You claim to have a good reason, with no real justification that I've
seen. P.J. Plauger apparently does have a good reason; he needs to
write code that his customers can compile either as C or as C++. I
haven't seen anyone else make a coherent argument in favor of casting
the result of malloc().

[...]
Write:

char* p = (char*)malloc(n *sizeof(char*)) ;

and both C and C++ compilers will accept your code.


Write

char *p = malloc(n);

or

some_type *p = malloc(n * sizeof *p);

and use a C compiler. Or use a "new" operator and use a C++ compiler.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #41
On Fri, 19 Nov 2004 23:26:05 UTC, "E. Robert Tisdale"
<E.************ **@jpl.nasa.gov > wrote:
Write:

char* p = (char*)malloc(n *sizeof(char*)) ;

and both C and C++ compilers will accept your code.


Twitsdale is posting crap once again. Twitsdale is unable to learn C
as defined by the standard because he thinks ther is no other C
compiler as Wincrap existent on the real world.

Put twitsdale into your filters and you bewares yourself always of the
crap this bloody ignorant craps out of his ass.

There is really NO, absolutely NO reason to cast the result of a
function that returns a pointer to void. But here are thousend reasons
you invoke the lands of undefined behvior. When you writs C++ you have
in no ways a reason to use malloc() - new will always be better. When
you have to write C - use a C-compiler, when you have to write C++
then you have to use a C++-comiler.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #42
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanfor d.edu>
wrote:
"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.


No, implementation defined behavior only.
What problem do you envision with type-casting it?


undefined behavior as always by casting a result of a function that
returns pointer to void and is called without prototype in sight.
Implemenation defined behavior can be tolerable - undefined behavior
is never.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #43
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanfor d.edu>
wrote:
"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.


No, implementation defined behavior only.


Here is what the standard says:

If an invalid value has been assigned to the pointer, the
behavior of the unary * operator is undefined.83)

If malloc(0) returns a null pointer, then this is sufficient to
makes its behavior undefined. If malloc(0) return a non-null
pointer, then this quote from the standard holds:

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.

A violation of a "shall" requirement yields undefined behavior:

If a ``shall'' or ``shall not'' requirement that appears
outside of a constraint is violated, the behavior is
undefined.

Why do you think that dereferencing malloc(0) yields only
implementation-defined behavior?
What problem do you envision with type-casting it?


undefined behavior as always by casting a result of a function that
returns pointer to void and is called without prototype in sight.


I don't see how this is specific to malloc(0), and I don't see
that this is the issue at hand anyhow.
Implemenation defined behavior can be tolerable - undefined
behavior is never.


Only in programs intended to be completely portable.
--
"What is appropriate for the master is not appropriate for the novice.
You must understand the Tao before transcending structure."
--The Tao of Programming
Nov 14 '05 #44
Herbert Rosenau <os****@pc-rosenau.de> scribbled the following:
On Fri, 19 Nov 2004 23:26:05 UTC, "E. Robert Tisdale"
<E.************ **@jpl.nasa.gov > wrote:
Write:

char* p = (char*)malloc(n *sizeof(char*)) ;

and both C and C++ compilers will accept your code.

Twitsdale is posting crap once again. Twitsdale is unable to learn C
as defined by the standard because he thinks ther is no other C
compiler as Wincrap existent on the real world. Put twitsdale into your filters and you bewares yourself always of the
crap this bloody ignorant craps out of his ass. There is really NO, absolutely NO reason to cast the result of a
function that returns a pointer to void. But here are thousend reasons
you invoke the lands of undefined behvior. When you writs C++ you have
in no ways a reason to use malloc() - new will always be better. When
you have to write C - use a C-compiler, when you have to write C++
then you have to use a C++-comiler.


Furthermore, Trollsdale used the wrong type in his sizeof operation.
The correct type would be what the pointer points at, not the pointer
type itself. sizeof *p would have worked much better.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"Normal is what everyone else is, and you're not."
- Dr. Tolian Soran
Nov 14 '05 #45
Hello,

Herbert Rosenau <os****@pc-rosenau.de> schrieb:
When you writs C++ you have in no ways a reason to use malloc() - new
will always be better.


If I want to implement my own operator new, there are legit reasons to
call malloc on my own, even in C++.

But this is getting OT in this newsgroup here.

Regards,
Spiro.

--
Spiro R. Trikaliotis
http://www.trikaliotis.net/
http://www.viceteam.org/
Nov 14 '05 #46
On Sat, 20 Nov 2004 23:26:21 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanfor d.edu>
wrote:
"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.


No, implementation defined behavior only.


The return from malloc is implementation defined but must be either a null
pointer or an unusable pointer. Dereferencing either of those is undefined,
by definition....
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #47
On Sun, 21 Nov 2004 11:46:27 +0100, in comp.lang.c , Spiro Trikaliotis
<ne*********@tr ikaliotis.net> wrote:
Hello,

Herbert Rosenau <os****@pc-rosenau.de> schrieb:
When you writs C++ you have in no ways a reason to use malloc() - new
will always be better.
If I want to implement my own operator new,


But this isn't writing in C++, this is writing a compiler... :-)
there are legit reasons to
call malloc on my own, even in C++.
If you want to implement your own operator new, you'd be better advised to
use processor-specific memory management primitives.
But this is getting OT in this newsgroup here.


indeed.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #48
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message
news:cn******** **@nntp1.jpl.na sa.gov...
Write:

char* p = (char*)malloc(n *sizeof(char*)) ;

and both C and C++ compilers will accept your code.


Right : neither will catch that you don't get the difference between char and
char* !

A compromise solution :

#define MALLOC(count, type) ((type *)malloc((count ) * sizeof(type)))

and use it without a cast :

char *p = MALLOC(n, char);

that will work in both C and C++, and enforce consistency between allocation and
use.

Of course a compiler that does not complain about calling a function without
proper prototype is either broken or misconfigured. Fix that first.

Chqrlie.
Nov 14 '05 #49
In <92************ @brenda.flash-gordon.me.uk> Flash Gordon <sp**@flash-gordon.me.uk> writes:
On Fri, 19 Nov 2004 01:11:17 GMT
Keith Thompson <ks***@mib.or g> wrote:
Da*****@cern.ch (Dan Pop) writes:
[...]
> Or, if you prefer macros:
>
> #define XMALLOC(size) malloc(size == 0 ? 1 : size)
> #define YMALLOC(size) (size == 0 ? NULL : malloc(size))


Your XMALLOC is probably clearer than the one I came up with, but I'm
going to show it off because I think it's kinda clever.

#define XMALLOC(size) malloc((size) + ((size)==0))

(Yes, I habitually parenthesize references to arguments to
function-like macros; it's easier than figuring out when it isn't
necessary.)


Of course, either macro is a potential problem if you do
p = XMALLOC( size_array[i++] );


The names are spelled in upper case to warn the user that they're macros,
not functions. If the user chooses to ignore the warnings, he gets
exactly what he deserves.

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

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
3300
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
3320
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
19137
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
9647
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
10356
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
10162
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...
1
10100
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
9959
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
8988
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...
0
6744
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
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3665
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.