The Digital Group Interview Question
Developer Program EngineersCountry: India
Interview Type: Phone Interview
free uses a pointer to free up the memory. if u do free of one pointer its memory is freed. Now when u allocate arrray of intergers using new u have the first address of array and also no number of elements in the array so just use for loop inside for loop write free(p++) and it will free up the entire array.
- int *a = new int[10];
for(int i = 0; i < 10; i++) {
free(a + i);
}
it would crash.
- int *a = new int[10];
free(a);
It simply free the desired memory. All heap blocks were freed -- no leaks are possible
When I checked the binary with Valgrind, it reported an error
mismatch free / delete / delete []
1) malloc: you cannot use delete with malloc, as no constructor is called during memory allocation and while delete is used on that memory it will call destructor which will lead to seg fault.
2)new: you can use either delete or free. But the problem with using free is that the class desctructor is not called and hence there will be problems later on.
Hence try to stick with malloc-free and new-delete
1) malloc: you cannot use delete with malloc, as no constructor is called during memory allocation and while delete is used on that memory it will call destructor which will lead to seg fault.
2)new: you can use either delete or free. But the problem with using free is that the class desctructor is not called and hence there will be problems later on.
Hence try to stick with malloc-free and new-delete
Before calling free() on a pointer for which memory was allocated using new() call the destructor of that class and then invoke free();
The new() keyword does the below 2 operations
1.Allocate memory using malloc by invoking the "Operator new"
2.call the constructor.
The delete() keyword does the below 2 operations
1.call the destructor.
2.Deallocate the memory using free by invoking the "Operator delete"
Conceptually, yes, that's how new and delete work. However, what you said about being able to interchange calling the destructor + calling free with calling delete is not correct.
Memory allocated using new is not guaranteed to be implemented in the same way, or to use the same heap, as memory allocated using malloc.
In short -- you cannot interchange delete and free no matter what you do!
Neither of those is correct. Quite simply, if you allocated using new, you must de-allocate with delete. If it was new[], then use delete[]. If it was malloc, use free. No other combination of those operators is correct.
- eugene.yarovoi October 23, 2011