Take the 2-minute tour ×

what will be correct form of this code in c?

char *x = malloc(100);


#include <stdlib.h>
#include <stdio.h>
int main(){
    char *x=malloc(100);
    //in c++
    // char *x=new char[100];

     return 0;

here is errors

1>------ Build started: Project: memory_leaks, Configuration: Debug Win32 ------
1>Build started 8/1/2010 2:32:21 PM.
1>  Creating directory "c:\users\david\documents\visual studio 2010\Projects\memory_leaks\Debug\".
1>  Creating "Debug\memory_leaks.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>  memory_leaks.cpp
1>c:\users\david\documents\visual studio 2010\projects\memory_leaks\memory_leaks\memory_leaks.cpp(5): error C2440: 'initializing' : cannot convert from 'void *' to 'char *'
1>          Conversion from 'void*' to pointer to non-'void' requires an explicit cast
1>Build FAILED.
1>Time Elapsed 00:00:00.64
share|improve this question
What's wrong with this? –  KennyTM Aug 1 '10 at 11:29
Well, it is correct. Just don't forget calling free when you are done with it. –  AraK Aug 1 '10 at 11:30
You're apparently compiling this with a C++ compiler, not C. –  Greg Hewgill Aug 1 '10 at 11:33
What's wrong is that your question asks about how to compile something in C, but you aren't even using C. You are using C++. The line of code you gave would not produce the same errors if you were using a C compiler. –  Greg Hewgill Aug 1 '10 at 11:46
@davit, in C what you have above is valid code, in C++ a casting is needed (and normally one would use new/delete instead). –  Claptrap Aug 1 '10 at 12:09
show 2 more comments

2 Answers

up vote 8 down vote accepted

You have valid C code, but you're trying to compile with a C++ compiler. (In fact, if you renamed your source to memory_leaks.c, your development environment would probably automatically invoke a C compiler; with memory_leaks.cpp it invokes a C++ compiler.)

C and C++ are different languages. C++ looks like C with extra stuff, because it evolved from a language that was C with extra stuff. But it's now its own language. Don't mix them up.

In particular, if you add a cast before malloc, you might get C++ code that compiles, but you won't get good C++ code. Don't do it: if you're programming in C++, use new; if you're programming in C, use a C compiler.

share|improve this answer
add comment

and you have to cast to "char *" like:

char * x = (char *)malloc(100*sizeof(char));


void *malloc(int);
share|improve this answer
Not true. You don't have to cast in C (though you can). –  el.pescado Aug 1 '10 at 12:26
add comment

Your Answer


