1
votes

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.

4
Closely related (almost a duplicate) stackoverflow.com/questions/3278864/…jogojapan
Also here: stackoverflow.com/questions/5115556/…. I am going to vote to close as duplicate.jogojapan
Avoid putting using directives in headers.GManNickG
I was keeping searching questions about "malloc" instead of "namespace std "so I didn't find any closely related question. Thanks for your links, jogojapan.Mark Z.

4 Answers

3
votes

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.

2
votes

malloc() is defined in <cstdlib> so you must include it at the top of your file.

using namespace std; just tells the compile that you're using that particular namespace, and has nothing to with including any library methods.

In any case, you really should be using new rather than malloc for dynamic allocation when using C++.

1
votes

using namespace std; tells the compiler, I'm "using" the std namespace, so pretend like I'm in the std namespace for lookups and don't ask me to say std:: every time.

The trouble is, there is nothing in the std namespace (yet)!

You need to #include the header for malloc to be declared.

And even then, it's global -- not in std.

0
votes

Use 'new' for memory allocation. 'using namespace std' has nothing to do with stdlib.h IF you still want to use malloc() add this on the top

#include<cstdlib>

Good luck!