21

我在 Fedora 下使用 g++ 来编译一个 openGL 项目,其中包含以下代码:

textureImage = (GLubyte**)malloc(sizeof(GLubyte*)*RESOURCE_LENGTH);

编译时,g++ 错误说:

error: ‘malloc’ was not declared in this scope

添加#include <cstdlib>并不能修复错误。

我的 g++ 版本是:g++ (GCC) 4.4.5 20101112 (Red Hat 4.4.5-2)

4

3 回答 3

32

您应该new在 C++ 代码中使用,而不是malloc这样new GLubyte*[RESOURCE_LENGTH]。当您#include <cstdlib>将其加载malloc到命名空间std时,请参阅std::malloc(或#include <stdlib.h>改为)。

于 2011-08-10T07:53:25.273 回答
18

你需要一个额外的包含。添加<stdlib.h>到您的包含列表。

于 2011-08-10T08:02:46.433 回答
6

在 Fedora 上的 g++ 中重现此错误:

如何尽可能简单地重现此错误:

将此代码放在 main.c 中:

#include <stdio.h>
int main(){
    int *foo;
    foo = (int *) std::malloc(sizeof(int));
    *foo = 50;
    printf("%d", *foo);
}

编译它,它返回一个编译时错误:

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));
                                     ^  

像这样修复它:

#include <stdio.h>
#include <cstdlib>
int main(){
    int *foo;
    foo = (int *) std::malloc(sizeof(int));
    *foo = 50;
    printf("%d", *foo);
    free(foo);
}

然后它编译并正确运行:

el@apollo:~$ g++ -o s main.c

el@apollo:~$ ./s
50
于 2014-06-13T20:15:35.567 回答