g++ error: ‘malloc’ was not declared in this scope

2019-04-18 09:15发布

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)

标签: c++ g++ malloc
3条回答
疯言疯语
2楼-- · 2019-04-18 10:00

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

查看更多
Juvenile、少年°
3楼-- · 2019-04-18 10:06

You need an additional include. Add <stdlib.h> to your list of includes.

查看更多
forever°为你锁心
4楼-- · 2019-04-18 10:06

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
查看更多
登录 后发表回答