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 | #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 char (elements) in the new array.
//
// This will be on the HEAP (segment of memory).
s[0] = 'Y';
s[1] = 'o';
s[2] = 'p';
s[3] = 'e';
s[4] = '\0';
// BAD
// char* s = (char*) malloc(sizeof(*s) * num_chars); // no unnecessary cast
// char* s = malloc(sizeof(char) * num_chars); // use sizeof(expr)
// Note: sizeof(..) does not access or evaluate the expression so there
// is no problem using it before it is initialized.
printf("%s\n", s);
// FIXME: This is a leak because we haven't called free(…).
return EXIT_SUCCESS;
}
/*
==20653== HEAP SUMMARY:
==20653== in use at exit: 5 bytes in 1 blocks
==20653== total heap usage: 1 allocs, 0 frees, 5 bytes allocated
==20653==
==20653== 5 bytes in 1 blocks are definitely lost in loss record 1 of 1
==20653== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==20653== by 0x4005C8: main (malloc_intro_with_leak.c:7)
==20653==
==20653== LEAK SUMMARY:
==20653== definitely lost: 5 bytes in 1 blocks
==20653== indirectly lost: 0 bytes in 0 blocks
==20653== possibly lost: 0 bytes in 0 blocks
==20653== still reachable: 0 bytes in 0 blocks
==20653== suppressed: 0 bytes in 0 blocks
*/
/* 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.