954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

type casting

what happened if we do't typecast return value of malloc
like that

int *a=malloc(10);

Sukhbir
Light Poster
31 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0
 

Casting malloc

int *a = malloc(10 * sizeof *a);
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Most compilers will complain because malloc() returns void* and, in C++, you need to cast void* to the type you are mallocing.

Generally, you should use 'new' and 'delete' rather than malloc, for at least these three good reasons:
1) You don't need to cast
2) As Dave pointed out, malloc(10) allocates 10 BYTES, not 10 ints
3) Constructors are not called. Not a big deal with ints, but a huge deal with objects.

In this case,

int* a = new int[10];
delete [] a;

note the need for [] in the delete; if you used [] in new, use them in delete.

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

Using C memory allocation routines in C++ programs is BAD FORM.

subtronic
Junior Poster
117 posts since Aug 2003
Reputation Points: 44
Solved Threads: 1
 

>int *a = malloc(10 * sizeof *a);
Most compilers will complain because malloc() returns void* and, in C++, you need to cast void* to the type you are mallocing.

Generally, you should use 'new' and 'delete' rather than malloc, for at least these three good reasons:
1) You don't need to cast
2) As Dave pointed out, malloc(10) allocates 10 BYTES, not 10 ints
3) Constructors are not called. Not a big deal with ints, but a huge deal with objects.

In this case,

int* a = new int[10];
delete [] a;

note the need for [] in the delete; if you used [] in new, use them in delete.
>Using C memory allocation routines in C++ programs is BAD FORM.
I see nothing in the original post that suggests either C++ or C. As the answer is directly related to the language, don't you three think it makes sense to ask before going off on your favorite tangent?

>what happened if we do't typecast return value of malloc
In C, nothing because pointers are implicitly converted to and from void without the need for a cast. In fact, it is best to avoid the cast in C because it hides errors.

In C++, you would get a compile-time error because C++ does not bless implicit pointer conversions to and from void. A cast is required, but it's better to use new in C++ for several reasons that I won't mention because that wasn't your question.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You