g++ error: ‘malloc’ was not declared in this scope
Solution 1
You should use new
in C++ code rather than malloc
so it becomes new GLubyte*[RESOURCE_LENGTH]
instead. When you #include <cstdlib>
it will load malloc
into namespace std
, so refer to std::malloc
(or #include <stdlib.h>
instead).
Solution 2
You need an additional include. Add <stdlib.h>
to your list of includes.
Solution 3
Reproduce this error in g++ on Fedora:
How to reproduce this error as simply as possible:
Put this code in main.c:
#include <stdio.h>
int main(){
int *foo;
foo = (int *) std::malloc(sizeof(int));
*foo = 50;
printf("%d", *foo);
}
Compile it, it returns a compile time error:
el@apollo:~$ g++ -o s main.c
main.c: In function ‘int main()’:
main.c:5:37: error: ‘malloc’ was not declared in this scope
foo = (int *) malloc(sizeof(int));
^
Fix it like this:
#include <stdio.h>
#include <cstdlib>
int main(){
int *foo;
foo = (int *) std::malloc(sizeof(int));
*foo = 50;
printf("%d", *foo);
free(foo);
}
Then it compiles and runs correctly:
el@apollo:~$ g++ -o s main.c
el@apollo:~$ ./s
50
![Ovilia](https://i.stack.imgur.com/NGwHl.png?s=256&g=1)
Ovilia
Web designer and programmer. Personal site: http://zhangwenli.com
Updated on June 14, 2020Comments
-
Ovilia about 4 years
I'm using g++ under Fedora to compile an openGL project, which has the line:
textureImage = (GLubyte**)malloc(sizeof(GLubyte*)*RESOURCE_LENGTH);
When compiling, g++ error says:
error: ‘malloc’ was not declared in this scope
Adding
#include <cstdlib>
doesn't fix the error.My g++ version is:
g++ (GCC) 4.4.5 20101112 (Red Hat 4.4.5-2)
-
templatetypedef almost 13 yearsIf you do need to use a
malloc
-like function, in C++, consider using the functionoperator new
, which interfaces with the rest of the memory system (it throws exceptions, calls the new handler if memory can't be found, etc.) -
Sander De Dycker almost 13 yearsSince using
#include <stdlib.h>
dumps all declared names in the global namespace, the preference should be to use#include <cstdlib>
, unless you need compatibility with C. -
Keith Thompson about 10 yearsAs I understand it,
#include <cstdlib>
will importmalloc
and friends into thestd
namespace, and may or may not import them into the global namespace, while#include <stdlib.h>
will import them into the global namespace, and may or may not import them into thestd
namespace. -
Ravinder Payal almost 8 yearserror: invalid conversion from 'void*' to 'char**' [-fpermissive] result = std::malloc(sizeof(char*) * count);
-
Eric Leschinski almost 8 yearsThe error you are posting is unrelated to the malloc issue addressed in my post. If you have a new question please use the "Add Question" button in the upper right.
-
Eric Leschinski almost 8 yearsmalloc always returns void. Please refrain from posting followup questions on answers that have nothing to do with your problem.