mirror of
https://github.com/janishutz/eth-summaries.git
synced 2026-01-12 08:08:25 +00:00
[SPCA] Restructuring, finish memory management in C, start dynamic memory management section
This commit is contained in:
@@ -14,6 +14,13 @@ struct MyStruct {
|
||||
int el2;
|
||||
};
|
||||
|
||||
// Like structs, but can only hold one of the values!
|
||||
union MyUnion {
|
||||
int ival;
|
||||
float fval;
|
||||
char *sval;
|
||||
};
|
||||
|
||||
int fun( int j ) {
|
||||
static int i = 0; // Persists across calls of fun
|
||||
short my_var = 1; // Block scoped (deallocated when going out of scope)
|
||||
@@ -27,7 +34,10 @@ int main( int argc, char *argv[] ) {
|
||||
}
|
||||
struct MyStruct test; // Allocate memory on stack for struct
|
||||
struct MyStruct *test_p = &test; // Pointer to memory where test resides
|
||||
test.el1 = 1; // Direct element access
|
||||
test_p->el2 = 2; // Via pointer
|
||||
struct MyStruct test2;
|
||||
union MyUnion my_uval; // Work exactly like structs for access
|
||||
test.el1 = 1; // Direct element access
|
||||
test_p->el2 = 2; // Via pointer
|
||||
test2 = test; // Copies the struct
|
||||
return 0;
|
||||
}
|
||||
|
||||
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