This code raises segmentation fault on the last line. Header is a pointer to a contiguous block of memory which is all 0, and dereferencing the remainder returns 0 which is probably related to the issue. I still feel like this should work though, what is the issue?
void setHeader(void *header, size_t payload) {
size_t *remainder = (size_t*)((char *)header + (payload + 4));
*remainder = payload;
}
Why do you think this should work? Unless the pointed-to object is sufficiently large that adding
payload + 4does not exceed the size of the object, the pointer arithmetic has undefined behavior. Even if the arithmetic is defined (e.g. if the object size is exactlypayload + 4), dereferencing the slot one past the end of an array has UB. You’ll need to make sure the object whose address you’re passing is sufficiently large in order for your code to work.