Skip to the task
Layout
Back to classic view
READTask 1 of 20 · step 1: The heap, malloc and freeThe stack and the heap
The stack and the heap in practice/11/

Variables on the stack disappear with the function, a heap block lives until free. malloc and the NULL check, n * sizeof *p, free and p = NULL, who frees it is written in the contract.

Details & hint

Until now the size of every array was known at compile time: Student s[MAX_STUDENTS]. The eleventh student doesn't fit, and with three of them 7 places are empty. Dynamic memory is allocated at run time, as much as needed.

The stack and the heap

stack (main)heap n = 10squares 149162536496481100 stack: gone when the function returnsheap: lives until you call free malloc(10 * sizeof *squares) = 40 bytes
  • The stack – a function's variables. They appear when the function is called and vanish when it returns. Their size is known at compile time.
  • The heap – memory the program asks for while running. It lives until the program gives it back.

malloc and free

#include <stdlib.h>

size_t n = 10;
int *squares = malloc(n * sizeof *squares);
if (squares == NULL) {
    printf("Out of memory.\n");
    return EXIT_FAILURE;
}
/* squares[0] ... squares[n - 1] */
free(squares);
squares = NULL;
  • malloc(bytes) returns a pointer to a new block of memory, or NULL if it got none. The contents are garbage, like an uninitialised variable.
  • sizeof *squares is the size of one element. If you later change int to double, the line stays correct.
  • free(p) gives the block back. Afterwards p still points at that place, but it isn't yours any more: assign NULL. free(NULL) does nothing – that's allowed.

Who frees it?

Every malloc has exactly one free. When a function returns new memory, say in its contract that the caller frees it:

/* Returns a new copy of s in dynamic memory, or NULL if there isn't enough.
   Before: s != NULL. After: the caller frees the copy with free. */
char *copy_string(const char *s);

Memory that is never freed is a leak: over time the program eats more and more memory.

practice 11 measurements.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_MEASUREMENTS 100
typedef enum { OK = 0, CANNOT_OPEN, BAD_LINE, TOO_MANY, WRITE_FAILED } Error;
/* A description of the error code for a person. */
const char *error_text(Error e) {
switch (e) {
case OK:
return "ok";
case CANNOT_OPEN:
return "cannot open the file";
case BAD_LINE:
return "not a number";
case TOO_MANY:
return "too many measurements";
case WRITE_FAILED:
return "write failed";
}
return "unknown error";
}
/* Prints how the work with the file path ended. */
void print_error(const char *path, Error e, int line_no) {
if (e == BAD_LINE) {
printf("%s, line %d: %s\n", path, line_no, error_text(e));
} else {
printf("%s: %s\n", path, error_text(e));
}
}
/* Reads one number per line into t[0..max-1].
Before: path, t, count, line_no != NULL, max > 0.
After: OK and *count numbers; otherwise an error code,
and *line_no is the number of the line it stopped at. */
Error read_measurements(const char *path, double t[], int max, int *count, int *line_no) {
assert(path != NULL && t != NULL && count != NULL && line_no != NULL);
assert(max > 0);
*count = 0;
*line_no = 0;
FILE *f = fopen(path, "r");
if (f == NULL) {
return CANNOT_OPEN;
}
Error result = OK;
char line[64];
while (fgets(line, sizeof line, f) != NULL) {
(*line_no)++;
char *end;
double x = strtod(line, &end);
while (isspace((unsigned char)*end)) {
end++;
}
if (end == line || *end != '\0') {
result = BAD_LINE;
break;
}
if (*count == max) {
result = TOO_MANY;
break;
}
t[*count] = x;
(*count)++;
}
fclose(f);
return result;
}
/* Writes the report to the file path.
Before: path != NULL, count >= 0. */
Error write_report(const char *path, int count, double average) {
assert(path != NULL && count >= 0);
FILE *out = fopen(path, "w");
if (out == NULL) {
return CANNOT_OPEN;
}
int a = fprintf(out, "Measurements: %d\n", count);
int b = fprintf(out, "Average: %.2f\n", average);
if (fclose(out) != 0 || a < 0 || b < 0) {
return WRITE_FAILED;
}
return OK;
}
int main(void) {
const char *path = "measurements.txt";
double t[MAX_MEASUREMENTS];
int count;
int line_no;
Error e = read_measurements(path, t, MAX_MEASUREMENTS, &count, &line_no);
if (e != OK) {
print_error(path, e, line_no);
return EXIT_FAILURE;
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += t[i];
}
double average = count > 0 ? sum / count : 0.0;
printf("Measurements read: %d\n", count);
printf("Average: %.2f\n", average);
const char *report = "report.txt";
e = write_report(report, count, average);
if (e != OK) {
print_error(report, e, 0);
return EXIT_FAILURE;
}
printf("Report written: %s\n", report);
const char *others[] = {"bad.txt", "missing.txt"};
for (int i = 0; i < 2; i++) {
e = read_measurements(others[i], t, MAX_MEASUREMENTS, &count, &line_no);
print_error(others[i], e, line_no);
}
return EXIT_SUCCESS;
}