This question was asked in the written round of a job interview:
#include<alloc.h>
#define MAXROW 3
#define MAXCOL 4
main()
{
int (*p)[MAXCOL];
p = (int (*)[MAXCOL]) malloc(MAXROW*(sizeof(*p)));
}
How many bytes are allocated in the process?
To be honest, I did not answer the question. I did not understand the assignment to p
.
Can anybody explain me what would be the answer and how it can be deduced?
Memory allocation failures can occur due to latencies that are associated with growing the size of a page file to support additional memory requirements in the system.
In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).
The problem with dynamic memory allocation is that it is not deallocated itself, developer responsibility to deallocate the allocated memory explicitly. If we cannot release the allocated memory, it can because of memory leak and make your machine slow.
It's platform dependent.
int (*p)[MAXCOL];
declares an pointer to an array of integers MAXCOL elements wide (MAXCOL of course is 4 in this case). One element of this pointer is therefore 4*sizeof(int)
on the target platform.
The malloc
statement allocates a memory buffer MAXROW times the size of the type contained in P. Therefore, in total, MAXROW*MAXCOL integers are allocated. The actual number of bytes will depend on the target platform.
Also, there's probably additional memory used by the C runtime (as internal bookeeping in malloc, as well as the various process initialization bits which happen before main
is called), which is also completely platform dependant.
p
is a pointer to an array of MAXCOL
elements of type int
, so sizeof *p
(parentheses were redundant) is the size of such an array, i.e. MAXCOL*sizeof(int)
.
The cast on the return value of malloc
is unnecessary, ugly, and considered harmful. In this case it hides a serious bug: due to missing prototype, malloc
is assumed implicitly to return int
, which is incompatible with its correct return type (void *
), thus resulting in undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With