Thursday, 22 August 2013

C: Trying to free malloc'd char array returned from function results in an error

C: Trying to free malloc'd char array returned from function results in an
error

I have a function to convert a short to a byte array here
char *GetBytesShort(short data)
{
char *ptr = (char *) malloc(sizeof(short));
memcpy(ptr, &data, sizeof(short));
return (char *) *ptr;
}
And, in my main.c, I call the function like this
char *data = GetBytesShort(10);
free(data);
However, whenever I try to free the memory, I get an error First-chance
exception at 0x5896586E (msvcr110d.dll) in Project1.exe: 0xC0000005:
Access violation reading location 0x00000004.
If there is a handler for this exception, the program may be safely
continued.
I'm using Visual Studios 2012 Ultimate edition. I've already set the
language to C in Properties -> C/C++ -> Advanced -> Compile As, but to no
avail. And my files have the .c extension, and not the .cpp
Thanks in advance!

No comments:

Post a Comment