thkang
thkang

Reputation: 11543

why malloc does not work without casting?

please consider the following code :

#include "stdafx.h"
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct Person *Person_create(char *name, int age, int height, int weight)
{
    struct Person *who = (struct Person*) malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

the curious line is

struct Person *who = (struct Person*) malloc(sizeof(struct Person));

I searched internet a bit for malloc() usages. about half of them are written with casting, others are not. on vs2010, without (struct Person*) cast an error emerges:

1>c:\users\juhyunlove\documents\visual studio 2010\projects\learnc\struct\struct\struct.cpp(19): error C2440: 'initializing' : cannot convert from 'void *' to 'Person *'
1>          Conversion from 'void*' to pointer to non-'void' requires an explicit cast

So what is a proper way to create a pointer and assign memory to it?

Upvotes: 2

Views: 1498

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129344

If you rename your file from struct.cpp, to struct.c, the compiler will do what you expect a C compiler to do, rather than do what a C++ compiler should do (as explained above). Visual Studio comes with a compiler that can do both C and C++, so it's just a case of naming the file correctly when you create it.

I'm not sure if renaming the file inside visual studio is enough, or if you have to add a new file called struct.c, copy the content from the existing file into it, and then delete teh original struct.cpp. The latter definitely works.

Upvotes: 1

ouah
ouah

Reputation: 145829

Because you are using a C++ compiler.

Casting malloc (assuming the type is not void *) is required in C++. In C, it is not required and it is even recommended to not cast malloc.

In C there is an implicit conversion from void * to all object pointer types during assignment.

void *p = NULL;
int *q = p;  // valid in C, invalid in C++

Upvotes: 14

Related Questions