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

Ovi*_*lia 20 c++ malloc g++

我在Fedora下使用g ++来编译一个openGL项目,该项目有以下几行:

textureImage = (GLubyte**)malloc(sizeof(GLubyte*)*RESOURCE_LENGTH);
Run Code Online (Sandbox Code Playgroud)

编译时,g ++错误说:

error: ‘malloc’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

添加#include <cstdlib>不能解决错误.

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

use*_*653 31

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

  • 如果你*需要使用类似于malloc`的函数,在C++中,考虑使用函数`operator new`,它与内存系统的其余部分接口(抛出异常,如果内存可以调用新的处理程序'找到,等等) (2认同)
  • 因为使用`#include <stdlib.h>`转储全局命名空间中的所有声明的名称,所以首选应该使用`#include <cstdlib>`,除非你需要与C兼容. (2认同)

dra*_*oot 17

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


Eri*_*ski 5

在Fedora上用g ++重现这个错误:

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

将此代码放在main.c中:

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

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

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));
                                     ^  
Run Code Online (Sandbox Code Playgroud)

修复如下:

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

然后它编译并正确运行:

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

el@apollo:~$ ./s
50
Run Code Online (Sandbox Code Playgroud)