Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation Problem

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?

like image 446
Flash Avatar asked Dec 09 '10 06:12

Flash


People also ask

What is memory allocation problem?

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.

What happens if memory allocation fails?

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).

What are the problems of dynamic memory allocation?

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.


2 Answers

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.

like image 133
Billy ONeal Avatar answered Sep 17 '22 12:09

Billy ONeal


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.

like image 22
R.. GitHub STOP HELPING ICE Avatar answered Sep 21 '22 12:09

R.. GitHub STOP HELPING ICE