Discussion:
would free() work in this situation...?
(too old to reply)
Chan Kevin Guy Kim
2003-12-09 19:14:53 UTC
Permalink
if i wrote something like...

void main(void)
{
int *array;
array=(int*)malloc(sizeof(int)*10);
array=&array[5];
free(array);
}

would the first 5 nodes (that were allocated before) not be
freed? or would free() know to free 10 allocated spaces?
Jim Clarke
2003-12-09 23:01:15 UTC
Permalink
Post by Chan Kevin Guy Kim
if i wrote something like...
void main(void)
{
int *array;
array=(int*)malloc(sizeof(int)*10);
array=&array[5];
free(array);
}
would the first 5 nodes (that were allocated before) not be
freed? or would free() know to free 10 allocated spaces?
The results are unpredictable. (In other words, C can do
anything it likes, including caused a segmentation fault.)
The reason is that free() requires as argument a pointer
returned by malloc(), and malloc() didn't return a pointer
to array[5].
--
Jim Clarke -- Dept. of Computer Science, University of Toronto
http://www.cs.utoronto.ca/~clarke

Loading...