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

Coding Techniques

Memory Allocation · Study material

One exit, one cleanup (goto done)

When a function allocates several things, failure can happen at any step. Start every pointer at NULL and jump to a single cleanup label; because free(NULL) does nothing, the cleanup frees everything that was actually allocated. The Linux kernel uses this pattern everywhere.

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

int process(size_t n) {
    int rc = -1;
    int *a = NULL, *b = NULL;

    a = malloc(n * sizeof *a);
    if (a == NULL)
        goto done;
    b = malloc(n * sizeof *b);
    if (b == NULL)
        goto done;

    for (size_t i = 0; i < n; i++) {
        a[i] = (int) i;
        b[i] = a[i] * 2;
    }
    rc = b[n - 1];

done:                            /* one exit: every path frees everything */
    free(b);                     /* free(NULL) is a safe no-op */
    free(a);
    return rc;
}

int main(void) {
    printf("%d\n", process(10));
    return 0;
}

Output

18

Overflow-safe allocation sizes

malloc(count * size) silently wraps around when the product exceeds SIZE_MAX, and you get a tiny block. Check before multiplying – or use calloc(), which does it for you.

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

void *alloc_array(size_t count, size_t size) {
    if (size != 0 && count > SIZE_MAX / size)      /* count * size would wrap around */
        return NULL;
    return malloc(count * size);
}

int main(void) {
    void *huge = alloc_array(SIZE_MAX / 2, 4);
    printf("%s\n", huge == NULL ? "refused: size overflow" : "allocated");

    void *ok = alloc_array(100, sizeof(int));
    printf("%s\n", ok != NULL ? "100 ints allocated" : "failed");
    free(ok);
    return 0;
}

Output

refused: size overflow
100 ints allocated

Ownership rules

Decide, for every pointer, who frees it – and write it down in the function's comment.

char *read_name(void);            /* returns heap memory: the CALLER must free() it */
void  print_name(const char *s);  /* borrows s: never frees it */
void  list_destroy(struct list *l); /* takes ownership: frees l and its nodes */

A function that returns allocated memory should say so in its name or comment, and C23's [[nodiscard]] stops callers from ignoring the pointer.

Finding memory bugs with sanitizers

Modern compilers find leaks and memory errors for you. Use these flags while developing and testing:

# GCC or Clang: stop at the first invalid read/write, double free or use-after-free
cc -std=c17 -g -fsanitize=address,undefined -fno-omit-frame-pointer app.c -o app
./app

# Leaks are reported automatically at exit on Linux (LeakSanitizer)
# Valgrind is an alternative that needs no recompiling:
valgrind --leak-check=full ./app

Safe memory habits

  • Check every malloc/calloc/realloc result.
  • Write p = malloc(n * sizeof *p).
  • Use tmp = realloc(p, n), then assign.
  • Set pointers to NULL after free().
  • Prefer calloc() when you need zeros or when count × size could overflow.
  • Use memmove() for overlapping copies.
  • Never realloc(p, 0) in C23 – call free(p).

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