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 54 7860
In article <30************ *@uni-berlin.de>, ti************* **@yahoo.com
says... Why this code fragment returns a valid pointer to a memory block???
-Neo
I've seen this before. Some versions of UNIX will return an error,
others will return a valid pointer. I'm not sure which is correct but I
found the 2nd situation to be more common and more useful as you don't
have to code round it - I've got a few +1's in some code just to
guarentee a valid pointer which happens to contain nothing. That way I
know the pointer has been initialised even it doesn't contain anything.
It's working like a flag as well as a place to store results.
-- http://www.beluga.freeserve.co.uk
"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)
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
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 !
- Ravi
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. -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
"Ravi Uday" <ra******@gmail .com> wrote in message
news:1100686594 .274808@sj-nntpcache-5... "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)
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
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 !
- Ravi
<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>
Peter Smithson <pg************ **********@yaho o.co.uk> wrote: In article <30************ *@uni-berlin.de>, ti************* **@yahoo.com says...
Why this code fragment returns a valid pointer to a memory block??? I've seen this before. Some versions of UNIX will return an error,
By which, I hope, you mean a null pointer, since causing a segfault or a
signal for malloc(0) is not conforming.
others will return a valid pointer. I'm not sure which is correct
Either.
Richard
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.
2. You are setting up an object whick you might extend later using
realloc(). However whether malloc(0) return null or not is immaterial to
this, either result can be passed to realloc(). So the latitude given by
the standard is harmless here. Of course you have the issue of freeing the
"object" for a non-null return.
Lawrence
Lawrence Kirby <lk****@netacti ve.co.uk> wrote: 2. You are setting up an object whick you might extend later using realloc(). However whether malloc(0) return null or not is immaterial to this, either result can be passed to realloc(). So the latitude given by the standard is harmless here. Of course you have the issue of freeing the "object" for a non-null return.
Even that is not a problem, since free(0) is harmless. No matter what
you get from malloc(), you can free() it.
Richard
On Wed, 17 Nov 2004 13:53:09 +0000, Richard Bos wrote: Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
2. You are setting up an object whick you might extend later using realloc(). However whether malloc(0) return null or not is immaterial to this, either result can be passed to realloc(). So the latitude given by the standard is harmless here. Of course you have the issue of freeing the "object" for a non-null return.
Even that is not a problem, since free(0) is harmless. No matter what you get from malloc(), you can free() it.
True, my intent was more along the lines of you have consider calling free()
appropriately for a non-null return, whereas if the return was always
null in this case you wouldn't have to worry.
However given the possibility extending the object to non-zero length
there's likely to be code to handle freeing anyway, so it probably turns
out to be a non-issue.
Lawrence
"Ravi Uday" <ra******@gmail .com> wrote in message
news:1100686594 .274808@sj-nntpcache-5... "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)
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
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 !
- Ravi
O'kay thanks for pointing it out.
But what should be the suggested behavior and why?
Is a valid pointer right way?
I think NULL is a better option? isn't it???
-Neo This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: mike79 |
last post by:
hi all..
if I wanted to malloc a struct, say the following:
struct myStruct1
{
int number;
char *string;
}
|
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
|
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...
|
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...
|
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
| |
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
|
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 */
|
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
|
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.
|
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...
|
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...
| |
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |