I am developing a program in C++ and encounter this error when I run this code:
short readshort() {
short val=0;
(&val)[1]=data.front(); data.pop_front();
(&val)[0]=data.front(); data.pop_front();
return val;
}
This is the error I get:
Run-Time Check Failure #2 - Stack around the variable 'val' was corrupted.
I should mention now, that "data" is defined with std::list data;
I think I know what is the problem, but I cannot think of an easy solution. I think this error is cause by the "val" being stored in the stack, and not as a pointer. When I try to access the data pointer by "val" I get this error.
The solution I thought about was allocating "val" like this:
short readshort() {
short* val=new short;
val[1]=data.front(); data.pop_front();
val[0]=data.front(); data.pop_front();
return *val;
}
But I can't see a way to delete "val" once I have returned it without having to delete it outside the function every time. Is there a way this can be done in C++ wihtout a memory leak? I havn't seen anyone split a variable type (e.g. short) into bytes using "(&val)[1]" before, and wondered if this was because it gave rise to a number of problems, or is it just not a known method?
Coming back to the real question, how can I make these two bytes into short (or large data type)? And is there a better way of doing this than what I have tried?
One last thing, I know that java has an automatic garbage collector that cleans up memory leaks automatically. Does C++ offer the same kind of device? I heard somthing about Smart Pointers, but I don't know what they are ;)
This is safe and simple:
int16_t readshort()
{
union { int16_t s; char val[2]; } u;
u.val[1]=data.front(); data.pop_front();
u.val[0]=data.front(); data.pop_front();
return *(int16_t*)u.val;
}