1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int main(int argc, char** argv) {
int* a_n = malloc(sizeof *a_n); // equivalent to malloc(4) but always use expression.
// malloc(…) takes a number of bytes to allocate.
// ... and returns an address (void*) on the heap.
// - In C, you can assign a void* to an ▒▒* and vice versa (as long as one is void*).
// - The memory will be continguous (all together)
// - ... and NOT initialized to anything in particular.
*a_n = 5; // "store 5 at address a_n"
printf("*a_n == %d\n", *a_n); // "print the value at address a_n."
//
free(a_n);
// free(…) takes a memory address
// - Address must be an address previously returned by malloc(…).
// - That address will be on the heap.
// - You must call free exactly once for every call to malloc.
return EXIT_SUCCESS;
}
// WRONG: int* a_n = malloc(sizeof(int));
//
// sizeof *a_n ⇔ sizeof(*a_n) ⇔ sizeof(int)
// sizeof is an operator not a function or macro
// sizeof takes an expression or a type... always use an expression if possible
//
// WRONG: int* a_n = (int*) malloc(sizeof(…));
//
// Do not use typecasts unless you can articular why it is necessary and safe.
// The cases where a typecast is necessary and safe are few and far between.
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.