If free() knows the length of my array, why can't I ask for it in my own code?
Posted
by Chris Cooper
on Stack Overflow
See other posts from Stack Overflow
or by Chris Cooper
Published on 2010-04-16T05:49:03Z
Indexed on
2010/04/16
5:53 UTC
Read the original article
Hit count: 238
I know that it's a common convention to pass the length of dynamically allocated arrays to functions that manipulate them:
void initializeAndFree(int* anArray, int length);
int main(){
int arrayLength = 0;
scanf("%d", &arrayLength);
int* myArray = (int*)malloc(sizeof(int)*arrayLength);
initializeAndFree(myArray, arrayLength);
}
void initializeAndFree(int* anArray, int length){
int i = 0;
for (i = 0; i < length; i++) {
anArray[i] = 0;
}
free(anArray);
}
but if there's no way for me to get the length of the allocated memory from a pointer, how does free()
"automagically" know what to deallocate? Why can't I get in on the magic, as a C programmer?
Where does free()
get its free (har-har) knowledge from?
© Stack Overflow or respective owner