Mehta said:
Hi all,
What is the significance of "malloc(0)"?
It doesn't return a NULL pointer, then what does it return?
Where one can use such a "malloced" pointer?
You may be able to use it as a tag of some sort, if you are generally
doing comparisons of pointers. Let's say you had a list of pointers to
data, but you wanted a few "special" values such as EMPTY and UNKNOWN.
Let's say your list node looks like this:
struct list_node
{
void *data;
struct list_node *next;
}
You could do the following:
void *EMPTY, *UNKNOWN;
int main()
{
EMPTY = malloc(0);
UNKNOWN = malloc(0);
...
}
void process_list (struct list_node *l)
{
struct list_node *cur;
for(cur = l; cur != NULL; cur = cur->next)
{
if(cur->data == UNKNOWN)
{
printf("Data Unknown\n");
}
if(cur->data == EMPTY)
{
printf("Data Empty\n");
}
else
{
process_data(cur->data);
}
}
}
Anyway, any time you had a pointer to a certain type of data (maybe char
*), but needed some special values that aren't necessarily of that type
(like UNKNOWN or EMPTY above), you could malloc(0) to make sure that you
have a valid, unique pointer, but doesn't take up much memory.
Jon