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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7007468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:20:05  来源:igfitidea点击:

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

c++g++malloc

提问by Ovilia

I'm using g++ under Fedora to compile an openGL project, which has the line:

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

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

When compiling, g++ error says:

编译时,g++错误说:

error: ‘malloc' was not declared in this scope

Adding #include <cstdlib>doesn't fix the error.

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

My g++ version is: g++ (GCC) 4.4.5 20101112 (Red Hat 4.4.5-2)

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

回答by user786653

You should use newin C++ code rather than mallocso it becomes new GLubyte*[RESOURCE_LENGTH]instead. When you #include <cstdlib>it will load mallocinto namespace std, so refer to std::malloc(or #include <stdlib.h>instead).

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

回答by dragonroot

You need an additional include. Add <stdlib.h>to your list of includes.

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

回答by Eric Leschinski

Reproduce this error in g++ on Fedora:

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

How to reproduce this error as simply as possible:

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

Put this code in main.c:

将此代码放在 main.c 中:

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

Compile it, it returns a compile time error:

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

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

Fix it like this:

像这样修复它:

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

Then it compiles and runs correctly:

然后它编译并正确运行:

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

el@apollo:~$ ./s
50