c++错误:' malloc '未在此范围内声明

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

本文关键字:范围内 声明 错误 c++ malloc      更新时间:2023-10-16

我在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)

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

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

在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