Search code examples
cbytedynamic-memory-allocation

How many bytes are dynamically allocated in the following code segment?


Assuming that a memory address occupies 4 bytes and a char occupies 1 byte:

char** t;
t = malloc(5 * sizeof(char*));
int i;
for (i = 0; i < 5; i++)
 t[i] = malloc(sizeof(char) * (i+1));

Solution

  • 35 bytes (Look below for breakup)

    char** t;
    t = malloc(5 * sizeof(char*));  // 5 * 4 = 20 bytes
    int i;
    for (i = 0; i < 5; i++)
     t[i] = malloc(sizeof(char) * (i+1)); //1 + 2 + 3 + 4 + 5 = 15 bytes