Memory deallocation question
I just want to make sure that I'm properly deallocating memory in my program...
I build a dynamically allocated 2D array in one function ( build_proc_table() ) and return the array to where the function was called ( main() ). The array is stored in a variable in main() and I made a "destructor" function that deallocates the memory, but the destructor开发者_运维问答 is called in main() as well, not where the memory for the array was originally allocated at ( in build_proc_table() )...
I don't get any errors or anything ( compile time or run time ) and the program functions exactly as I wan't it to, I just want to make sure that I'm not causing a memory leak.
Any memory you allocate manually has a lifetime that is not bound to its scope. As long as the memory allocated somewhere is deallocated somewhere else at a later time, you'll be fine. It doesn't matter where it's called from.
Without knowing which language you're using, specifics are difficult. However, as long as you aren't changing the reference between allocation and deallocation, it doesn't matter where the memory is deallocated. However, if you change what memory address is being addressed between allocation and deallocation (without deallocating before the change), you will have a memory leak.
In C++, for example...
int main(){
int* j = new int[10];
j = new int[10];
delete j;
}
This will be a memory leak because the first array is not deleted. This is obviously a simplified example being one dimensional and not using functions.
精彩评论