g++错误: 'malloc'在此作用域中未声明

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)


1
你是否在使用命名空间?你的malloc代码是否在命名空间中? - Patrick B.
你确定这个项目应该使用g++编译吗? - Austin Mullins
3个回答

33

在 C++ 代码中,应该使用 new 而不是 malloc,所以应该变成 new GLubyte*[RESOURCE_LENGTH]。当你 #include <cstdlib> 时,它会将 malloc 加载到命名空间 std 中,所以请参考 std::malloc(或者改为 #include <stdlib.h>)。


2
如果你确实需要使用类似于 malloc 的函数,在 C++ 中,可以考虑使用 operator new 函数,它与内存系统的其他部分进行交互(如果无法找到内存,则抛出异常,调用新处理程序等)。 - templatetypedef
2
由于使用 #include <stdlib.h> 会将所有声明的名称都倒入全局命名空间中,因此最好使用 #include <cstdlib>,除非需要与 C 兼容。 - Sander De Dycker
据我所知,#include <cstdlib>将会把malloc和相关函数导入到std命名空间中,并且可能会或者可能不会将它们导入到全局命名空间中。而#include <stdlib.h>则会将它们导入到全局命名空间中,但是可能会或者可能不会将它们导入到std命名空间中。 - Keith Thompson

19

你需要添加一个额外的包含文件。在你的包含列表中添加<stdlib.h>


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

错误:从'void*'到'char**'的转换无效[-fpermissive] result = std::malloc(sizeof(char*) * count); - Ravinder Payal
你发布的错误与我帖子中提到的malloc问题无关。如果你有新的问题,请使用右上角的“添加问题”按钮。 - Eric Leschinski
malloc总是返回void。请不要在与您的问题无关的答案上发布后续问题。 - Eric Leschinski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接