M
mathog
The title says it all.
Many loops start with a pointer at the beginning of an allocated block,
and when the loop completes the pointer is one byte past the end of the
allocated block. As far as I can remember, a free() operating on the
pointer with that value has always released the memory.
Does free() work like that because the language standard mandates it, or
is it just something that pretty much all of the compilers do?
This code fragment illustrates the issue:
int count = 100;
int *block = (int *) malloc(count * sizeof(int));
memset(block,1,count*sizeof(int)); /* put some data in */
for(; count; count--, block++){
printf("%d ",*block);
}
/* block is now 1 byte past the end of the allocated memory */
free(block); /* <-- Language says what about this??? */
Storing the first value of block and then using free() with that later
is not hard to do - I just wonder if it is necessary in this case.
Thanks,
David Mathog
Many loops start with a pointer at the beginning of an allocated block,
and when the loop completes the pointer is one byte past the end of the
allocated block. As far as I can remember, a free() operating on the
pointer with that value has always released the memory.
Does free() work like that because the language standard mandates it, or
is it just something that pretty much all of the compilers do?
This code fragment illustrates the issue:
int count = 100;
int *block = (int *) malloc(count * sizeof(int));
memset(block,1,count*sizeof(int)); /* put some data in */
for(; count; count--, block++){
printf("%d ",*block);
}
/* block is now 1 byte past the end of the allocated memory */
free(block); /* <-- Language says what about this??? */
Storing the first value of block and then using free() with that later
is not hard to do - I just wonder if it is necessary in this case.
Thanks,
David Mathog