/* ** $Id: memory.c 774 2008-02-16 01:24:16Z phf $ ** ** Very simple first example of using malloc() and free() ** for dynamic memory allocation. Note: Don't ever free() ** anything you did not malloc() previously, it's plain ** wrong, somewhat mean, and just a hassle in the end. ** ** Note that I should do more complete error checking in ** the code below, but I don't have time since I need to ** post this ASAP. I just use assert() where you should ** do *real* error checking. Sorry. */ #include #include #include int main(int argc, char *argv[]) { // make sure we have an argument assert(argc > 1); // We'll let the user specify how large an array we // should build. int size = (int) strtol(argv[1], NULL, 10); // make sure the size is positive assert(size > 0); // Now we'll actually get the memory for an array // of that size. int *array = malloc(size * sizeof(int)); // make sure we got the memory assert(array != NULL); // Compute a table of squares, just to do something // that initializes the array; malloc() does *not* // promise that everything will be set to 0, might // want to use calloc() for that... for (int i = 0; i