c++错误:' malloc '未在此范围内声明
g++ error: ‘malloc’ was not declared in this scope
我在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
相关文章:
- 错误:未在此范围内声明'reverse'
- 错误:"imread"未在此范围内声明
- 未在此范围内声明错误 'xy'
- Socklen_t未在此范围内声明
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 'num1'未在此范围内声明
- 如何找到在本地范围内声明的变量的地址?
- NT状态未在此范围内声明
- 变量未在此范围内声明 数组线性搜索
- 包含文件中的 Typdef "未在此范围内声明"
- 'ClassName'和'ClassInstance'未在此范围内声明
- C++ 中的类之间的数据重新循环 - 错误:'<class name>'未在此范围内声明
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 如何修复错误:"vreinterpretq_u32_f64"未在此范围内声明 - 在Android上使用Eigen构建
- 如何修复C++中的"arrStud未在此范围内声明"错误
- 错误:"SHGetKnownFolderPath"未在此范围内声明
- 错误:'Sprite'未在此范围内声明