Shy Student
Shy Student

Reputation: 99

Malloc syntax in C

In the books I read that the syntax for malloc is malloc(sizeof(int)) but in one of doubly linked list program I see the following:

newnode=(struct node *)malloc(sizeof(struct node))

What is (struct node*) doing here? What is this entire code doing? btw, the code for the struct in the program is as below.

struct node
{
char line[80];
struct node *next,*prev;
};

struct node *start=NULL,*temp,*temp1,*temp2,*newnode;

Thank you

Upvotes: 3

Views: 23288

Answers (5)

Inisheer
Inisheer

Reputation: 20794

The code is dynamically creating a pointer to a single type of struct node. In most versions of C, the (struct node *) cast is not needed, and some argue that it shouldn't be used. If you remove the cast, it will be a void*, which can be used for any type.

Therefore:

newnode = (struct node*)malloc(sizeof(struct node));

is roughly equivalent to:

newnode = malloc(sizeof(struct node));

See: Specifically, what's dangerous about casting the result of malloc?

Note 1: If you are using Visual Studio to write your C code, it will give you red underlining if you don't cast the result of malloc. However, the code will still compile.

Note 2: Using malloc in C++ code requires you to cast the result as shown in your example.

Upvotes: 5

Pradheep
Pradheep

Reputation: 3819

malloc returns a void pointer .

(struct node*) does a explicit conversion from void pointer to the target pointer type

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

You should pass the number of bytes that you want malloc to allocate as argument. That is why in this code sample you use sizeof(struct node) telling C to allocate the number of bytes needed for a struct node variable. Casting the result like is shown in this code is bad idea by the way.

Upvotes: 2

Brad
Brad

Reputation: 11515

"malloc" returns a void-pointer. (struct node *) is type-casting the result of malloc to a "node struct pointer", which is (undoubtibly) what "newnode" is.

Upvotes: 1

user405725
user405725

Reputation:

You ran into a very bad code. C programmers never cast a result of malloc(). Not only it is not needed but can be harmful.

Upvotes: 3

Related Questions