c++ - 在函数中分配内存以返回给用户

标签 c++ heap-corruption

我有一个函数,它通过串行发送一个命令,然后接收一个未知大小的响应。使用

(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++ - 在函数中分配内存以返回给用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036854/

相关文章:

java - 如何像UAC窗口一样控制键盘和鼠标

c++ - strdup 导致堆损坏

c++ - 与转换相关的堆损坏错误

C 程序仅在 Visual Studio 中的 Debug模式下,以编程方式更改 argv 在程序退出后会出现堆损坏错误。如何解决?

c++ - 动态内存和链表

c++ - 如何从字符中检索整数值?

c++ - 自定义 vector 类中的堆损坏错误

c++ - InDev 基于位的加密程序中未知的 C++ 堆损坏,C++ 编程的新手

c++ - C++中的图像处理

c++ - 多线程程序中捕获SIGSEGV、SIGFPE等信号