Reputation: 90
I wrote a driver code for query packet . but I got bluescreen issue and I took dump also . after analyzing I got error on particular line mentioned below . why this error occur ? can I check unsigned char pointer with zero
?
my definitions :
typedef unsigned char u8_t ;
typedef unsigned char s8_t ;
typedef unsigned short u16_t ;
my function
void function1 (u8_t ntype , u16_t nvar , u8_t *pbuffer)
{
HEADER packet = (HEADER)allocatemry( sizeof(HEADER) + (pbuffer == 0 ? 0 : var)) ; //header is a structure with contain union .
packet->type = ntype ;
if ( pbuffer != 0 ) //got bluescreen issue . windbug pointed here
{
packet->variant.variable = network(nvar) ;
}
else
{
packet->variant.variable = nvar ;
}
}
please help me .
Upvotes: 0
Views: 333
Reputation: 238441
The error is very unlikely to have occurred on the shown line. The line before it or possibly after seem much more likely.
And the source of the problem is this:
HEADER packet = (HEADER)allocatemry( sizeof(HEADER) + (pbuffer == 0 ? 0 : var)) ; //header is a structure with contain union .
Unlike the comment at the end of the line claims, HEADER
must actually be a pointer rathern than a structure. This is evidenced by it being a return type of allocation function and the indirection operator here: packet->type
.
So, since HEADER
is a pointer, your're allocating memory enough for a single pointer and possibly a few more bytes depending on pbuffer
and var
instead of allocating enough bytes for an object of some sort. If that is not enough memory for your object, then this results in an invalid memory access when the program assumes that enough memory was allocated.
You can get the number of needed bytes to store an object that can be pointed by HEADER
like this: sizeof std::remove_pointer<HEADER>::type
.
Now that you've revealed the actual type of the struct in a comment, this is a simpler way: sizeof _MYHEADER
.
By the way, identifiers that begin with an underscore followed by an uppercase letter are reserved, so _MYHEADER
is not allowed. I recommend getting rid of the typedefs entirely, name your struct MYHEADER
and use MYHEADER*
for the pointers to avoid confusion in the future.
Upvotes: 2