3. malloc() example
-
malloc.c:
// test malloc() and free() // #include <stdio.h> #include <stdlib.h> int main( void) { size_t n = 0; char *p, *q = NULL; printf( "Enter list of sizes:\n"); while( scanf("%zi",&n) == 1) { p = q; q = malloc(n); // intentionally allocating new space before freeing old free(p); printf( "%zi bytes at %p\n", n, (void *) q ); } return 0; } /* sample run: Enter list of sizes: 20 20 bytes at 0x55c6fc852a80 20 20 bytes at 0x55c6fc852aa0 10 10 bytes at 0x55c6fc852a80 */