C++ – error when using g++: ‘malloc’ was not declared in this scope

cg++mallocnamespaces

I am practicing g++ to compile my code yet the error "malloc was not declared in this scope" keeps emerging at the beginning. The pieces of my code related to this error looks like:

/*------Basic.h--------*/
using namespace std;

/*------A.h------------*/
class A{
 private:
  double* _data;
 public:
 A(int N);
}

/*------A.cpp----------*/
A::A(int N){
  _data=(double*)malloc(N*sizeof(double));
}

This problem never emerges when I use Microsoft Virtual Stdio. I therefore tried to add a line

#include <stdlib.h>

to Basic.h, and the error disappears. Now I am wondering why this kind of thing happens. Hasn't "namespace std" already include stdlib.h? Thanks a lot.

Best Answer

Namespaces and include files are two totally different things. You need to

#include <stdlib.h>

or, equivalently,

#include <cstdlib>

in order to get access to the declarations in that header file.

Your using-declaration

using namespace std;

on the other hand, means that you can use identifiers that are part of the namespace std, i.e. that were declared inside

namespace std {
  /*...*/
}

without prepending std:: each time.

For example, if you include <string>, you can use the data type std::string, but if you also add using namespace std;, you can use that data type simply as string.

Note, however, that malloc is not defined inside any namespace, so in order to use that, you need only to include stdlib.h.

Note For the difference between stdlib.h and cstdlib, see here.