the example is wrong , 13 is not aligned to 9 . in the line of code where you compute the offset rv = 7 and not 3
@ravishankar7972 Жыл бұрын
Offset = 6 is correct, rv should have returned 9 instead of 13.
@ravishankar7972 Жыл бұрын
If storing offset needs at least 4 bytes of space I don’t see this as a good solution either.
@dimabirenbaum9200 Жыл бұрын
Thank you for the video. One comment, for completeness of the code I think we can add a check "if(rv == NULL) return NULL;". Since malloc can fail on allocation.
@guuu6566 Жыл бұрын
You are absolutely correct, this sort of check is probably prudent for completeness.
@sohamehta Жыл бұрын
@@guuu6566 thanks for responding!
@revanthrajashekar5983 Жыл бұрын
in case the offset is less, aren't we allocating more memory than actually requested ?
@guuu6566 Жыл бұрын
Yes and no (if I understand your question correctly). Yes, we are always allocating more memory than requested; and in fact we are always allocating more memory than necessary (we should probably subtract `1` from our malloc request). But no: this is independent of the runtime offset calculated; we over-allocate in malloc to handle any possible returned alignment. Interestingly, there's actually another issue in this code (which may pop-up as a runtime failure on systems which require aligned memory load/stores): `storage` may not be at a valid memory offset for a uint32_t. In particular, if `alignment` is less than `4`. This question was intended for large alignment values; but we should either fix it for small alignments, or add a check to reject alignment
@sohammehta810 Жыл бұрын
@@guuu6566 thanks!
@ravishankar7972 Жыл бұрын
@@guuu6566I had the same notion, well summarized👏
@guuu656611 ай бұрын
To elaborate a bit further: The address pointed to by the local variable storage may not be 4-byte aligned. And if this code was ran on a system that required aligned stores, then it would presumably fail. Yes, if we put an appropriate restriction on alignment, we could avoid the problem. But that likely goes against the spirit of the question. If my goal was to make the simplest change to this code to resolve this concern, I would do something along the lines of: uint32_t temp = offset + sizeof(uint32_t) memcpy(storage, &temp, sizeof(uint32_t)); With the presumption that memcpy would resolve any alignment concerns. We would of course have to similarly use memcpy to read this value in the aligned-free function. If we wanted to avoid memcpy, then we could do another calculation to figure-out the appropriate aligned location for storage. Something along the lines of storage = ROUND_DOWN(storage, 4) (i.e. Shift storage "down" in memory such that it becomes aligned). Then also do the same within free.
@bonafontciel Жыл бұрын
I just want to give you feedback to improve your videos. Please don’t use white background it hurts people’s eyes specially for those coding day and night