Reputation: 351
I am trying to open a project that was developed using a version I dont know. gcc 4.4 is already installed on my red hat linux. its giving multiple errors. one of which is on the function malloc... it says "invalid arguments. candidates are void * malloc(?)".. while i am passing an integer variable to this function "malloc(size)".. can any one help me what is the problem..
umair
Upvotes: 0
Views: 1973
Reputation: 1853
You should prefer using C++ "new" and "delete" operators over malloc. malloc returns 0 in case of error, new throws an exception (which I consider to be the "good" approach)
http://www2.research.att.com/~bs/bs_faq2.html#malloc
Otherwise, the prototype for malloc is:
void* malloc(size_t size);
So to allocate a int, you would:
int* my_int = (int*) malloc(sizeof(int));
The reason you need to cast via "(int*)" the result of "malloc" is because malloc returns a void*. C++ will not permit assigning a void* to a int*. You could use a C++ static_cast instead of C cast if you prefer.
Upvotes: 4
Reputation: 538
you have a syntax error somewhere. please give us the exact line number. it's not a problem with malloc, the compiler thinks you are trying to pass malloc to something.
Upvotes: 0
Reputation: 14471
The gcc version should not make any difference in how malloc operates. The newer versions may be more pedantic though.
It's probably because the return value is a 'void*' and you're using a 'char*' pointer. You can probably use a cast:
char* p;
p = (char*) malloc( n );
Upvotes: 0
Reputation: 1045
You need to cast the malloc function when using it in c++. As it returns void* by default.
char* chars ;
chars = (char*) malloc(10*sizeof(char));
^
|
Also for gcc is for c and g++ is used for c++, but that doesn't matter much i guess.
Upvotes: 0