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

时间:2011-08-10 07:49:21

标签: c++ g++ malloc

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

3 个答案:

答案 0 :(得分:30)

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

答案 1 :(得分:17)

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

答案 2 :(得分:5)

在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
相关问题