简体   繁体   中英

Does gcc version affect functions like malloc?

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

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.

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.

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 );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM