Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
malloc Function
Why does malloc(0) return valid memory address? What's the use?
✍: FYIcenter
malloc(0) does not return a non-NULL under every implementation. An implementation is free to behave in a manner it finds suitable, if the allocation size requested is zero. The implmentation may choose any of the following actions:
* A null pointer is returned.
* The behavior is same as if a space of non-zero size was requested. In this case, the usage of return value yields to undefined-behavior.
Notice, however, that if the implementation returns a non-NULL value for a request of a zero-length space, a pointer to object of ZERO length is returned! Think, how an object of zero size should be represented?
For implementations that return non-NULL values, a typical usage is as follows:
void func ( void ) {
   int *p; /* p is a one-dimensional array,
   whose size will vary during the
   the lifetime of the program */
   size_t c;
   p = malloc(0); /* initial allocation */
   if (!p) {
      perror ("FAILURE");
      return;
   }
   /* ... */
   while (1) {
      c = (size_t) ...; /* Calculate allocation size
*/
      p = realloc ( p, c * sizeof *p );
      /* use p, or break from the loop */
      /* ... */
   }
   return;
}
Notice that this program is not portable, since an implementation is free to return NULL for a malloc(0) request, as the C Standard does not support zero-sized objects.
2007-02-26, 7438👍, 0💬
Popular Posts:
Can you explain what is “AutoPostBack” feature in ASP.NET ? If we want the control to automatically ...
How To Calculate Expressions with SQL Statements? - MySQL FAQs - Introduction to SQL Basics There is...
How will you freeze the requirement in this case? What will be your requirement satisfaction criteri...
Have you ever worked with Microsoft Application Blocks, if yes then which? Application Blocks are C#...
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 1...