简体   繁体   中英

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!

return (char *) *ptr;

*ptr is a char , the value pointed by ptr to be precise, that you are casting back to a char* .

You need just to return ptr .

This line:

return (char *) *ptr;

Should be this:

return ptr;

What you were doing in your original code is dereference the ptr , returning the first byte of data , then cast that to a pointer. This means that you ended up with a pointer with an invalid address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM