Hi lately i have been studying the malloc and calloc functions for dynamically allocating memory. I thought the form was:

(data_type*) malloc(data_size);

But then I stumbled onto this code snippet on a tutorial site:

#include <cstdlib>
    void *malloc( size_t size );

Why is the data type void?
Is my understanding of the malloc and calloc functions wrong or is this website wacky?
Oh and is the * after void for the pointer returned?

malloc returns a void* to the memory allocated and you need to ensure that you type cast it to the correct type.

void *malloc ( size_t size );

This is the function prototype, and as Agni stated it returns a void pointer. Since this is the function prototype you do not use this syntax when calling the function and infact you use the syntax you originally posted. Here is a small example

int q = 34;
char *test;
test = (char*)malloc(q);
...
free( test );

The snippet above will create a character array (c-string) of length 33, since 1 space is need for the null terminator. Be sure to read about the use of free(), it's essential!

Chris

malloc(<size>) just allocates a memory space for the size specified and returns a void * pointer pointing to the starting of the allocated memory block.
It returns a void * pointer (so that it can be type cast to any pointer type) and as you know void * pointer itself cannot be used to dereference any variable.So we need to typecast it according to our needs.
Example:

struct node{
int a ;
char b;
};
typedef struct node * NODE;

int main()
{
//Some code

NODE temp=(NODE)malloc(sizeof(struct node));

//Some code
}

General form:

<req>*<variable> = (<req>*)malloc(<size>);

The cast is bad in C. It hides potential errors such as forgetting to include <stdlib.h> and makes maintenance more difficult if you change the type of the pointer, so you'd best get into the habit of not casting the return value. Pointers are implicitly converted to and from void* with no complaints, so there's no good reason to cast anyway.

Here's a much improved form:

/* Allocate one object */
p = malloc ( sizeof *p );

/* Allocate N objects */
p = malloc ( N * sizeof *p );

The cast is a throwback from the dark ages when char* was the generic pointer rather than void* and there wasn't an explicit conversion rule in place.

commented: Thanks +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.