LearnFrenzy
Sign in Take a free test
C

C Programming · Topic 17 of 23

Memory Allocation Questions and Concepts

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Programs & Examples

Memory Allocation · Study material

A growing string builder with realloc()

Keep length and capacity next to the data, and double the capacity when it runs out. realloc(NULL, n) behaves like malloc(n), so the first append needs no special case.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct sb {
    char *data;
    size_t len, cap;
};

bool sb_append(struct sb *b, const char *s) {
    size_t n = strlen(s);
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 8;
        while (cap < b->len + n + 1)
            cap *= 2;
        char *tmp = realloc(b->data, cap);      /* realloc(NULL, n) works like malloc(n) */
        if (tmp == NULL)
            return false;
        b->data = tmp;
        b->cap = cap;
    }
    memcpy(b->data + b->len, s, n + 1);
    b->len += n;
    return true;
}

int main(void) {
    struct sb b = {0};
    const char *words[] = {"dynamic ", "memory ", "in ", "C"};
    for (int i = 0; i < 4; i++)
        if (!sb_append(&b, words[i]))
            return 1;
    printf("%s (len %zu, cap %zu)\n", b.data, b.len, b.cap);
    free(b.data);
    return 0;
}

Output

dynamic memory in C (len 19, cap 32)

Jagged array: Pascal's triangle with rows of different lengths

An array of row pointers lets each row have its own size. If any row fails to allocate, free the rows already made before giving up.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int rows = 5;
    int **t = malloc(rows * sizeof *t);          /* an array of row pointers */
    if (t == NULL)
        return 1;

    for (int r = 0; r < rows; r++) {
        t[r] = malloc((r + 1) * sizeof *t[r]);   /* row r has r + 1 numbers */
        if (t[r] == NULL) {
            while (r--)
                free(t[r]);
            free(t);
            return 1;
        }
        t[r][0] = t[r][r] = 1;
        for (int c = 1; c < r; c++)
            t[r][c] = t[r - 1][c - 1] + t[r - 1][c];
    }

    for (int r = 0; r < rows; r++) {
        for (int c = 0; c <= r; c++)
            printf("%d ", t[r][c]);
        printf("\n");
        free(t[r]);
    }
    free(t);
    return 0;
}

Output

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links