Challenge your understanding of manual memory allocation, deallocation, and error handling in C and C++. Evaluate key concepts like pointers, heap versus stack, and common pitfalls in managing dynamic memory safely and efficiently.
Which function should you use to allocate a dynamic array of 10 integers on the heap in C, ensuring that all elements are initially set to zero?
Explanation: The calloc function allocates memory for an array and initializes all bytes to zero, making it ideal when you want initialized memory. malloc only allocates memory but does not initialize it, which could lead to unpredictable values. realloc is used to resize previously allocated memory, not to make new allocations from scratch. alloc is not a standard memory management function in C, so using it would result in a compilation error.
When you allocate memory for an object in C++ using new, which operator must you use to properly free the memory?
Explanation: delete is used in C++ to deallocate memory allocated by new, ensuring that destructors are called and the memory is released. free is used in C for memory allocated with malloc, calloc, or realloc, but not for new in C++. remove is a function generally used for files, not memory. dispose is not a memory management function in C++.
Consider a function in C that allocates memory for an integer pointer with malloc but does not call free before the function ends. What does this situation describe?
Explanation: Not freeing heap-allocated memory leads to a memory leak, where the memory remains allocated but is no longer accessible. A stack overflow would occur if too much stack memory is used, which is unrelated to failing to free malloc allocations. A dangling pointer occurs when memory is freed but the pointer still references it. Null pointer exception describes dereferencing a null pointer, not forgetting to free memory.
What is a key distinction between memory allocated on the stack and memory allocated on the heap in C/C++?
Explanation: Stack memory is automatically managed and released when a function exits, while heap memory must be freed manually to avoid leaks. Contrary to another option, stack memory is reclaimed immediately after the function returns, unlike heap memory which persists until freed. Both stack and heap memory have limitations, but stack size is often more limited. Typically, stack memory is faster to access than heap memory, not the other way around.
If you access a pointer in C/C++ after you have called free or delete on it, this is known as what?
Explanation: After memory is freed, any pointer still referencing that memory becomes a dangling pointer, and accessing it can cause undefined behavior. Null pointer dereference occurs if you try to use a pointer set to NULL, not one that points to freed memory. Double-free error happens when memory is freed twice, not just accessed after being freed. Buffer overflow is unrelated; it involves writing outside the bounds of a block of memory.