mirror of
https://github.com/janishutz/eth-summaries.git
synced 2026-03-14 17:00:05 +01:00
[SPCA] Restructuring, finish memory management in C, start dynamic memory management section
This commit is contained in:
22
semester3/spca/code-examples/00_c/02_memory/00_memory.c
Normal file
22
semester3/spca/code-examples/00_c/02_memory/00_memory.c
Normal file
@@ -0,0 +1,22 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
int main( int argc, char *argv[] ) {
|
||||
long *arr = (long *) malloc( 10 * sizeof( long ) ); // Allocate on heap
|
||||
if ( arr == NULL ) // Check if successful
|
||||
return EXIT_FAILURE;
|
||||
arr[ 0 ] = 5;
|
||||
|
||||
long *arr2;
|
||||
if ( ( arr2 = (long *) calloc( 10, sizeof( long ) ) ) == NULL )
|
||||
return EXIT_FAILURE; // Same as above, but fewer lines and memory zeroed
|
||||
|
||||
// Reallocate memory (to change size). Always use new pointer and do check!
|
||||
if ( ( arr2 = (long *) realloc( arr2, 15 * sizeof( long ) ) ) == NULL )
|
||||
return EXIT_FAILURE;
|
||||
|
||||
free( arr ); // Deallocate the memory
|
||||
arr = NULL; // Best practice: NULL pointer
|
||||
free( arr2 ); // *Can* omit NULLing pointer because end
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
int main( int argc, char **argv ) {
|
||||
int a[ 2 ];
|
||||
int *b = malloc( 2 * sizeof( int ) ), *c;
|
||||
a[ 2 ] = 5; // assign past the end of an array
|
||||
b[ 0 ] += 2; // assume malloc zeroes out memory
|
||||
c = b + 3; // mess up your pointer arithmetic
|
||||
free( &( a[ 0 ] ) ); // pass pointer to free() that wasn't malloc'ed
|
||||
free( b );
|
||||
free( b ); // double-free the same block
|
||||
b[ 0 ] = 5; // use a free()'d pointer
|
||||
// any many more!
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user