Become a memory accounting amateur

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2019-08-27 00:00:00 +00:00
parent 1e969e832f
commit efc4205416
10 changed files with 411 additions and 65 deletions

View File

@@ -4,22 +4,26 @@
#include <stdio.h>
#include <stdlib.h>
/* We do this in a separate function just to illustrate that
* this is allows for malloc memory! This is unlike regular stack
* variables which may be deallocated when the function returns. */
void *allocate_bytes(size_t nbytes) {
return malloc(nbytes);
}
int main(int argc, char **argv) {
int *is;
size_t nbytes, nints;
/* Decide how many ints to allocate. */
/* Decide how many ints to allocate.
* Unlike usual non-VLA arrays, the size is determined dynamically at runtime! */
if (argc < 2) {
nints = 2;
} else {
nints = strtoull(argv[1], NULL, 0);
}
nbytes = nints * sizeof(*is);
/* Allocate the ints.
* Note that unlike traditional stack arrays (non-VLA)
* this value does not have to be determined at compile time! */
is = malloc(nbytes);
is = allocate_bytes(nbytes);
/* This can happen for example if we ask for too much memory. */
if (is == NULL) {