|
From: John R.
|
> char* buf = malloc(5); > buf[7] = 0; > Valgrind correctly reports the problems, although incorrectly says that > buf[7] is a write 2 bytes beyond the end of the memory when it's 3 bytes > beyond. Under the schema that is used by average programmers, Purify is correct that a write to buf[7] is 3 bytes beyond the end of the block that was allocated by malloc(5): "Address 0x80b4927 is 3 bytes past end of a malloc'd block at 0x80b4920 of 5 bytes." The schema is: number the bytes. The address of the last allocated byte is &buf[4], and &buf[7] - &buf[4] is 3. &buf[5] is "one byte beyond the end." However, under the schema that is used by the most experienced and skillful C programmers, Valgrind is correct that a write to buf[7] is 2 bytes beyond the end of the block. The schema is: number the [zero-width] boundaries between the bytes, and associate a byte with its lower-numbered boundary. The end of the block is the _boundary_ associated with buf[5], and &buf[7] - &buf[5] is 2. &buf[5] is "zero bytes beyond the end" because the boundary between the byte associated with offset +4 and the byte associated with offset +5 _is_ the [zero-width] end of the block. -- |