I have a function which sends a command over serial, then receives a response of unknown size. Using
(ioctl(fd_, FIONREAD, &bytes_in_buffer);
I determine how much memory I need to allocate for my read.
//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;
}
I believe this is corrupting my stack, as my next function call breaks at
unsigned char * command = new unsigned char(3);
with the following:
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.
Could anyone offer some advice? I am at a loss, I thought passing the double pointer like that would allow me to allocate memory for the user...
Thank you in advance.
The line
(*response) = new unsigned char(response_size);
should read
(*response) = new unsigned char[response_size];
Your version allocates one unsigned character, and initializes it with the value response_size
.
response = new unsigned char[responze_size];
jrok 2012-04-05 22:31
response
if of type unsigned char**
, not of type unsigned char*
. It's an output parameter in C style - celtschk 2012-04-05 22:33
response
declaration in 3rd line (that one is unsigned char* - jrok 2012-04-05 22:34
*(unsigned char **)
that this problem occurs? My other allocation is fine? So unsigned char * test = new unsigned char(27)
is correct - Constantin 2012-04-05 22:35
new
elsewhere in the code as well - celtschk 2012-04-05 22:35
new
should be assigned to response
instead of (*response)
. Your problem is not related to the type of response
(that part you did right). Always when you want to allocate an array, you need to use the []
syntax (and remember to delete with delete[]
). Of course, probably a better solution would be to use vector
and forget about manual memory management - celtschk 2012-04-05 22:40