在函数中分配内存以返回给用户
Allocating Memory In A Function To Return to User
我有一个函数,它通过串行发送命令,然后接收未知大小的响应。 用
(ioctl(fd_, FIONREAD, &bytes_in_buffer);
我确定需要为读取分配多少内存。
//This code calls the function below
unsigned char CheckRefresh[] = {254, 124, 0};
unsigned char * response;
unsigned int size;
relay_board->SendCustomCommand(CheckRefresh, 3, &response, size);
ErrorCode SendCustomCommand(unsigned char * command, unsigned int command_size, unsigned char **response, unsigned int &response_size)
{
//Send the command
write(fd_, command, command_size);
// ... Omitting Polling Code to Get correct number of bytes ...
(ioctl(fd_, FIONREAD, &bytes_in_buffer);
//Now getting the response
response_size = (unsigned int)bytes_in_buffer;
(*response) = new unsigned char(response_size);
if(read(fd_, *response, response_size) < 0)
{
std::cout << "[ProXRSerial] SendCustomCommand: Read failed... -- Errno: " << errno << std::endl;
return Failed;
};
return Success;
}
我相信这会损坏我的堆栈,因为我的下一个函数调用在
unsigned char * command = new unsigned char(3);
与以下内容:
sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) -
__builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long)
(old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2
* (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) &&
((unsigned long)old_end & pagemask) == 0)' failed.
谁能提供一些建议? 我不知所措,我认为像这样传递双指针可以让我为用户分配内存......
提前谢谢你。
行
(*response) = new unsigned char(response_size);
应改为
(*response) = new unsigned char[response_size];
您的版本分配一个无符号字符,并使用值 response_size
对其进行初始化。
相关文章:
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- C++ - 将结构类型的数组传递给用户定义的函数
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- 为什么 free() 函数不将内存返回给操作系统?
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 如何在代码中创建抽象类,让蓝图扩展它,并将该蓝图返回给代码进行实例化?
- 如何将wchar_t字符串分配给用户定义类的 CString 成员
- 在我的 BST 实现中,我的 findNode 函数没有将父位置返回给其调用函数
- 如何将 2D 数组传递和返回给函数
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- CPU寄存器中返回的用户定义类型的C 对象.实例方法如何工作
- 使用 boost::p ython,如何将结构体向量作为字典列表返回给 Python
- 将新的 PyObject * 从 C++ 返回给 Python 最终会出现段错误
- 制作简单的CLI C 程序所需的知识,该程序为歌曲找到歌词并将其显示给用户
- 为什么我不能将数组值返回给主函数?
- 从我的c++应用程序调用c#dll(解析XML文件),将数组/列表返回给c++
- 如何将此的shared_ptr返回给拥有它的对象
- 将犰狳函数传递给用户定义的函数
- 如何将特殊值返回给父程序
- 在函数中分配内存以返回给用户