Why wouldn't gcc compile this trivial code that calls free() function? [closed]
I tried the following code on both codepad.org and ideone.com:
char* ptr = new char;
free( ptr );
Yes, I know it's undefined behavior, but I want to compile it and run it to see what happens.
Visual C++ 10 compiles it, but gcc which is used on the abovementioned sites says
error: expected constructor, destructor, or type conversion before ‘(’ token
Why wouldn't this code compile with gcc and how开发者_开发知识库 could I make it compile?
Here is your code (from your link):
#include <stdlib.h>
char* ptr = new char;
free( ptr );
free()
is a function, and at the namespace scope,you cannot write function-call-statement.
At namespace scope, you can only declare and define variables, and types. You can call a function in the initialization of a variable, however. So this is okay:
char* ptr = new char; //Note new is a function call!
But this is NOT okay:
free(ptr);
If you want to do that, then here is one trick:
const int ignore = (free(ptr), 0); //at namespace scope!
This is okay. Demo : http://ideone.com/8yymM
This code indeed will not compile. You have to add main()
call also.
#include <stdlib.h>
int main()
{
char* ptr = new char;
free( ptr );
return 0;
}
You can only call a function without a visible declaration in C. In C++ it is an error that must be diagnosed at compile time, it's not undefined behavior.
To call free
you must include the stdlib.h
header.
The proper code should be this one:
#include <stdlib.h>
int main()
{
char* ptr = new char;
free( ptr );
}
The error depends on the fact that free(ptr) at global scope is not seen as a function call, but as a declaration of an object of class free
:-o .
By the way, consider also that the opposite of ptr = new char
is not free(ptr)
, but delete ptr
. (free is the opposite of malloc
. new
calls malloc
, but does a bit more. As delete
calls free
but does something more).
Did you include <stdlib.h>
? It could be that the compiler doesn't recognize free
Because it's c++, so you need to use g++ instead of gcc.
精彩评论