I'm writing a generic sorting function with C using Visual Studio 2019.
I made an generic insertion sort function with prototype:
void insertion_sort(void* const arr, size_t left, size_t right, size_t width, _Cmpfun cmp)
where _Cmpfunc is typedef as
typedef int (*_Cmpfun) (const void*, const void*);
To test this function working I made an structure ELEMENT for the test like this.
typedef struct {
unsigned int score;
float data[3];
char comments[16];
} ELEMENT;
In order to save a data, I dynamically allocated memory like this.
char* top_ptr = (char*)malloc(sizeof(width));
Whenever I try to free() top_ptr after
memcpy(top_ptr, some_valid_pointer, width)
where some_valid_pointer is not NULL pointer and width is parameter of insertion_sort
, Visual Studio pops Heap corruption error.
This happens only after memcpy function is called.
If I do like this :
char* top_ptr = (char*)malloc(sizeof(width));
free(top_ptr);
it works fine.
I've search what is Heap corruption error in the web and found it occurs when memcpy function overwrites the invalid memory of structure variable.
I call function insertion_sort with width = sizeof(ELEMENT) in main so padding of struct variable is considered.
I have no idea what is the problem. What is wrong with my code?
CodePudding user response:
You're allocating memory of size sizeof(width):
char* top_ptr = (char*)malloc(sizeof(width));
but copying memory of size width:
memcpy(top_ptr, some_valid_pointer, width)
Most likely sizeof(width) < width, hence the heap corruption.
CodePudding user response:
width = sizeof(ELEMENT)
sizeof(ELEMENT), using back-of-the-envelope calculations, should be be in the neighborhood of about 30 bytes. That's how big your ELEMENT is.
char* top_ptr = (char*)malloc(sizeof(width));
Since width is a size_t, sizeof(size_t) will be either 4 or 8, depending upon whether you're compiling 32 or 64 bit code.
So, this will allocate 4 or 8 bytes. Far short of 30 bytes being memcpyed.
That's your heap corruption, right here.
