Learn C With Me #14 — Manual Memory Allocation, Part One | Live

In Lesson 14 of Learn C With Me, we begin Chapter 12 — Manual Memory Allocation from Beej’s Guide to C Programming.

This time, we explore how C programs can request memory dynamically, work with that memory through pointers, and release it when it’s no longer needed.

We cover:

  • What manual memory allocation means
  • The difference between automatic and dynamically allocated storage
  • Introducing malloc()
  • Allocating memory for integers and arrays
  • Using sizeof to calculate allocation sizes
  • Why malloc() returns a pointer
  • Checking allocation failures against NULL
  • Accessing dynamically allocated memory through pointers
  • Using array notation with allocated memory
  • Understanding the relationship between pointers and arrays
  • Releasing allocated memory with free()
  • Why accessing freed memory causes undefined behavior
  • Understanding memory leaks
  • Introducing calloc()
  • The difference between malloc() and calloc()
  • Zero-initialized allocated memory
  • Understanding allocation sizes and element counts
  • A brief look at integer overflow in allocation calculations
  • Revisiting pointer declarations and dereferencing
  • Understanding memory addresses and pointer values
  • How passing pointers to functions allows modification of original data
  • A discussion about CPU registers and assembly language

One of the main challenges in this lesson is understanding how a pointer relates to the memory allocated by malloc(). We spend time experimenting with the examples, inspecting values, and revisiting earlier pointer concepts.

We also discuss why memory management is the programmer’s responsibility in C. Allocated memory must eventually be released, and using memory after freeing it is undefined behavior.

Later, we explore calloc() and how it differs from malloc(), especially when it comes to initialization and allocation size calculations.

The lesson also takes an extended detour back into pointer fundamentals, including addresses, dereferencing, and how pointers relate to the actual contents of memory. We even explore some assembly language concepts to better understand what’s happening at a lower level.

As usual, we read the book, experiment with code, ask questions, make mistakes, and work through difficult concepts together with help from the live chat.

This is Part One of Manual Memory Allocation. We’ll return to the remaining material in the next lesson.

This is an interactive, follow-along live course. I am learning C alongside you, so expect questions, mistakes, experiments and plenty of discussion. No passive watching here — participate in the chat and work through the examples with us.

Homework #14 — Manual Memory Allocation, Part One

In Lesson 14 of Learn C With Me, we started learning about manual memory allocation.

We explored malloc(), free(), and calloc(), but also spent a lot of time revisiting pointers and trying to understand how they relate to memory.

For this homework, we’re going to keep things simple and practice the fundamentals.

Use only concepts we’ve covered so far, up to the material reached in Chapter 12 — Manual Memory Allocation.

1. Allocate a single integer

Write a program that dynamically allocates enough memory for one integer using malloc().

Store the value 42 in that memory and print it.

Your program must:

  • Use sizeof to determine the allocation size
  • Check whether malloc() returned NULL
  • Access the integer through a pointer
  • Release the allocated memory using free()

Question: What is the difference between the pointer variable and the memory it points to?

2. Allocate an array

Use malloc() to allocate enough memory for 10 integers.

Fill the array with:

0 5 10 15 20 25 30 35 40 45

Print all ten values using a loop.

Then release the allocated memory.

Questions:

  • How many bytes did you request from malloc()?
  • Why is sizeof(int) useful?
  • Can you use array indexing with dynamically allocated memory?

3. Compare malloc() and calloc()

Create two dynamically allocated arrays containing five integers each.

Allocate the first with:

malloc()

Allocate the second with:

calloc()

Initialize the first array yourself before reading its elements.

For the second array, inspect the initial values.

Questions:

  • What is the difference between malloc() and calloc()?
  • Why shouldn’t we assume memory returned by malloc() contains zeros?
  • Why does calloc() take two arguments?

Remember to release both allocations.

4. Revisit pointers

Start with:

int number = 10;
int *p = &number;

Print:

  • The value of number
  • The address of number
  • The value stored in p
  • The value obtained by dereferencing p

Then change the original value through the pointer:

*p = 25;

Print number again.

Question: Why did the original variable change?

5. Pass a pointer to a function

Write:

void double_value(int *p);

The function should double the integer pointed to by p.

Example:

int number = 21;

double_value(&number);

printf("%d\n", number);

Expected output:

42

Try to explain why passing a pointer allows the function to modify the original variable.

Bonus — Experiment with memory lifetime

Allocate memory for an integer, assign a value, print it, and release the memory.

Then answer these questions without executing an invalid memory access:

  • What would happen if you tried to dereference the pointer after free()?
  • Does free() automatically set your pointer to NULL?
  • What is a dangling pointer?
  • What is a memory leak?

After calling free(), try setting your pointer to NULL.

Why might this be useful?


Rules

Use only concepts covered in Learn C With Me so far.

You may use:

  • Pointers and dereferencing
  • Arrays
  • Functions
  • sizeof
  • malloc()
  • calloc()
  • free()
  • NULL

Do not use:

  • realloc()
  • Other allocation functions not yet covered
  • Concepts from later chapters

Important: Never dereference uninitialized memory or memory that has already been freed. Both can cause undefined behavior.

What we’re practicing

The main goal is to understand the relationship between:

A pointer variable, the memory address it stores, and the actual data stored at that address.

We also want to become comfortable with allocating memory, using it, and releasing it correctly.

As always, experiment, make predictions, compile the code, and read the compiler diagnostics.

If something doesn’t work, post your code and questions in the forum thread.

dont like how the ai keeps saying to make a function with ; at the end witch dose not compile nor is it a statment but owell here is what i did this time (darth is lasy and made this like 3 hours befor the weekly stream)

Code with spoilers for todays homework
#include <stdio.h>
#include <stdlib.h>


void double_value(int *p) {
    *p = *p * 2;
}

int main(void) {
    int *a = malloc(sizeof(int));
    if (a == NULL) {
        return 1;
    }
    *a = 42;
    printf("Number in a is : %d\n", *a);

    int *arr = malloc(sizeof(int) * 10);
    if (arr == NULL) {
        return 1;
    }
    printf("\nArray of numbers in memory shuld be 10 rows\n");
    for (int i = 0; i < 10; i++) {
        arr[i] = i * 5;
        printf("Array row : %d : Array number : %d\n", i + 1, arr[i]);
    }

    int *mal = malloc(sizeof(int) * 5);
    int *cal = calloc(5, sizeof(int));
    for (int i = 0; i < 5; i++) { mal[i] = i;}
    printf("\nMalloc array shuld be 5 rows\n");
    for (int i = 0; i < 5; i++) {
        printf("Array row : %d : Array number : %d\n", i + 1, mal[i]);
    }
    printf("\nCalloc array shuld be 5 rows of zeros\n");
    for (int i = 0; i < 5; i++) {
        printf("Array row : %d : Array number : %d\n", i + 1, cal[i]);
    }

    printf("\nPointer revisited\n");
    int number = 10;
    int *p = &number;
    printf(
        "Value of number : %d\nAddress of number : %p\nValue stored in p : %p\nValue obtained by dereferencing p : %d\n",
         number, &number, p, *p
    );
    *p = 25;
    printf("Mutated number with p : %d\n", number);

    printf("\nFunction with pointer used 21 base number dubbled\n");
    number = 21;
    double_value(&number);
    printf("%d\n", number);

    free(cal); 
    free(mal);
    free(arr);
    free(a);
    printf("Bonus point wen dereferansing freed item you get random bytes like this : %d\n", *a);
    return 0;
}
    /* bonus point again free dose not set pointer to null it keeps location but other programs are free to use it
    and dangeling pointer no clue what that is unles its like the *a example
    and memory leak is wen you write outside the asigned bytes in memory and you dont free them properly*/
picture of the result in terminal

Extra homework, non-AI.

It will show if you fully understand:

  1. pointers
  2. array-pointers equivalence
  3. memory allocation.

The task is to write a function which accepts 2 integer parameters:

  • rows and columns.

It should allocate a rows×columns matrix,
fill it with incrementing values starting from 0, and return it.

For example, function call make_matrix(2, 3) should create a matrix:

0 1 2
3 4 5

Hints:

  • a matrix can be represented as an array of rows aka an array of arrays

You will need to:

  1. Recognize what type that matrix will have.
  2. Correctly allocate memory for it.
    Hint: it’s going to be a multi-step process.
  3. Fill it using loops and array notation.
  • Extra question: let’s say your matrix is saved as variable m.
    What type will m[0] have?

I already did this one, don’t look at it until you are done with yours.

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

int** make_matrix(int rows, int collumns) {

  int **matrix = malloc(sizeof(int*) * rows);

  int i;
  for (i=0; i < rows; i++){
    matrix[i] = malloc(sizeof(int) * collumns);    
  }

  int k=0;
  for (i=0; i < rows; i++){
    // int k = 0;
    int j;
    for (j=0; j < collumns; j++){
      matrix[i][j] = k;
      k++;
    }
}

return matrix;
}

int main(void){
  int num_row = 6, num_col = 9, i, j;
  int **matrix = make_matrix(num_row, num_col);
  
  for (i = 0; i < num_row; i++) {
    for (j = 0; j < num_col; j++) {
      printf("%d\t", matrix[i][j]);
    }
    printf("\n");
  }
 
}

Also worth noting that my code, while it does work, has a flaw that needs to be corrected.

1 Like

Yes, that’s what I have been doing last night instead of live-streaming so I guess I can be forgiven for that one skip.

did this extra home work befor reading further

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

int *make_matrix(int row, int col) {
    int *matrix = malloc(sizeof(int) * row * col);
    if (matrix == NULL) {
        return NULL;
    }

    int counter = 0;
    for (int r = 0; r < row; r++) {
        for (int c = 0; c < col; c++) {
            matrix[r * col + c] = counter;
            // defenetly got stuck here tinking how i find it in memory for a wile
            //tryed matrix[r][c] but that did not go as planed
            
            if (counter == 0) {
                counter = 2;
            } else {
                counter *= 2;
            }
        }
    }
    return matrix;
}

void printf_matrix(int *matrix, int row, int col) {
    for (int r = 0; r < row; r++) {
        for (int c = 0; c < col; c++) {
            printf("%6d", matrix[r * col + c]);// had no ide i could just 3d with % thats great
        }
    printf("\n");
    }
}

int main(void) {
    int row = 4;
    int col = 4;
    int *matrix = make_matrix(row, col);
    if (matrix == NULL) {
        return 1;
    }

    printf("Printing a 3d matrix of 4 rows and 4 collumns:\n");
    printf_matrix(matrix, row, col);

    free(matrix);
    return 0;
}
// extra qustion m would be a int pointer and m[0] would be dereferanced in to an int

and a picture of the grid that i did 2 to the power

i see darth you used int ** that sure helps the [n1][n2] problem i had looks nice so far but why is // int k = 0 in forloop or was it just a mistake you keept to show us?
and notesed you used ‘\t’ in the print message what did that do again?

Not sure I got the instructions right. But I understand C arrays a bit better now than before, I think.

edit: Added another variant make_matrix2.

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

int *make_matrix(size_t nrows, size_t ncols) {
	size_t count = nrows * ncols;
	int *m = malloc(sizeof(int) * count);

	if (!m)
		return NULL;

	for (size_t i = 0; i < count; i++)
		m[i] = (int)i;

	return m;
}

int **make_matrix2(size_t nrows, size_t ncols) {
	int **rows = malloc(sizeof (int*));
	if (!rows)
		return NULL;
	
	int *values = make_matrix(nrows, ncols);
	if (!values) {
		free(rows);
		return NULL;
	}

	for (size_t r = 0; r < nrows; r++)
		rows[r] = &values[r * ncols];

	return rows;
}

void free_matrix2(int **matrix) {
	free(*matrix);
	free(matrix);
}

int main(void) {

	size_t nrows = 4;
	size_t ncols = 3;

	int *m = make_matrix(nrows, ncols);
	if (!m)
		return -1;

	// explicit calculation of row offset.
	// m[0] has type int
	for (size_t r = 0; r < nrows; r++) {
		for (size_t c = 0; c < ncols; c++)
			printf("%d ", m[r * ncols + c]);
		printf("\n");
	}
	printf("\n");

	// cast m to pointer of array.
	// m2[0] has type 'int *'
	int (*m2)[ncols] = (int (*)[ncols])m;
	for (size_t r = 0; r < nrows; r++) {
		for (size_t c = 0; c < ncols; c++)
			printf("%d ", m2[r][c]);
		printf("\n");
	}

	free(m);

	return 0;
}

looks good to me but this one realy confused me what dose it even do i see you set something there but dont understand all the extra * and () with int in front of it?

It’s a definition of a pointer to an array of ncols integer elements. Such solution is not clean but it works, too.

You allocated only one pointer to int. As the result, your loop has out of bounds write for any nrows > 1.

You probably wanted to write

	int **rows = malloc(nrows * sizeof (int*));

Yes, thanks. I should have spotted that one.