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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
    
    int num_chars = 5;
    char* s = malloc(sizeof(*s) * num_chars);
    // - sizeof(*s) gives you the number of bytes per char
    //
    // - num_chars is the number of chars (elements) in the new array.
    //
    // - This will be on the HEAP (segment of memory).
    //
    // - s itself is a local variable (on the stack) containing the address of the newly
    //   allocated block of memory on the heap.
    
    s[0] = 'Y';
    s[1] = 'o';
    s[2] = 'p';
    s[3] = 'e';
    s[4] = '\0';

    // COMMON MISTAKE #1:  unnecessary cast
    // char* s = (char*) malloc(sizeof(*s) * num_chars);
    //           ↑↑↑↑↑↑↑
    //             BAD! -- just omit the cast; it's not needed
    //

    // COMMON MISTAKE #2:  sizeof(type) instead of sizeof(expr)
    // char* s = malloc(sizeof(char) * num_chars);
    //                         ↑↑↑↑
    //                         BAD! -- use an expression (e.g., *s) instead
    //
    // Reason:  If we later change the declaration of s from `char* s` to some other
    //          type, we will be allocating the wrong amount of memory.

    // Note:  sizeof(..) does not access or evaluate the expression so there
    //        is no problem using it before it is initialized.

    printf("%s\n", s);

    free(s);   // IMPORTANT!  Without this, you have a MEMORY LEAK (-40% penalty)

    return EXIT_SUCCESS;
}
/*
==6755== HEAP SUMMARY:
==6755==     in use at exit: 0 bytes in 0 blocks
==6755==   total heap usage: 1 allocs, 1 frees, 5 bytes allocated
==6755==
==6755== All heap blocks were freed -- no leaks are possible
 */
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2017 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.