Post on 07-Apr-2022
transcript
C Heap Memory
Kurt Schmidt
Skipjack Solutions
December 13, 2021
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 1 / 21
Notes
Intended audience: Student who has working knowledge of PythonTarget compiler: I’ll try to center the discussion on C99 using gcc 7.4
• Code examples might have an accompanying link• Follow link to step through example at pythontutor.com• Does a nice job of graphically showing variables in memory, the
heap, and the stack
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 2 / 21
Heap Memory
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 3 / 21
Intro
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 4 / 21
Introduction to Heap Memory
• Values in C programs are stored:• In the static area (globals, static locals)• On the call stack (local variables, formal parameters)• Unamed, from the heap
• Heap, or free store• Nothing to do with the heap data structure• Memory managed by programmer
• Requested chunks of memory must be returned
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 5 / 21
Introduction (cont.)
• Programmer can request chunks of memory (using malloc)• Or calloc, realloc, or strdup1
• Programmer is responsible for returning chunk to the heap (usingfree)
• Chunks are unnamed• Must be accessed through a pointer
• Chunk can be any size• One int• Array of floats• person struct
• Good for resizeable arrays and strings, linked lists, . . .
1And, as we’ve seen, getlineKurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 6 / 21
Requesting Memory – malloc
void* malloc( size_t s ) ;
• s is the size of the requested memory chunk• Returns NULL upon failure• void* is a generic pointer
• Can not be dereferenced• Should be cast to needed type
int* p = NULL ;p = (int*) malloc( sizeof( int )) ;
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 7 / 21
Freeing Memory – free
void free( void* p ) ;
• Returns memory at address p to free store• Doesn’t affect pointer p at all
• p still points to freed chunk• Called a dangling pointer• Subtle, and dangerous error• Set to NULL when not in use
free( p ) ;p = NULL ;
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 8 / 21
Dangling Pointers
Dangling PointersA dangling pointer is a pointer that is pointing at something itshouldn’t.
• If we’re lucky it’s an illegal address, which will crash whendereferenced
Some examples:• Pointing at heap memory after it was freed• Pointing at a stack variable after the function returns• Uninitialised pointer pointing somewhere unintended• Running off the end of an array (buffer overrun
Some folk distinguish wild from dangling. Same problem, samedangers.
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 9 / 21
Memory Leak
Memory LeakA memory leak occurs when memory that is no longer needed is notreturned to the heap.
int *t = malloc( 18*sizeof( *t ))...t = NULL ; // That array is no longer accessible. Can’t free it
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 10 / 21
Example – malloc for individual items
int main( void ){
int *ip = (int*) malloc( sizeof( int )) ;int *jp = (int*) malloc( sizeof( int )) ;
*ip = 52 ;*jp = 88 ;
printf( "*ip is %d, and *jp is %d\n", *ip, *jp ) ;
free( ip ) ;ip = NULL ;jp = NULL ; /* MEMORY LEAK! */
return( 0 ) ;}
1https://goo.gl/52seVCKurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 11 / 21
Better – Returning Pointer to Heap Memory
int* foo( int i ){
int *rv = (int*) malloc( sizeof( int )) ;if( rv == NULL ) return NULL ;
*rv = i+3 ;return( rv ) ;
}
int main( void ){
int *p = foo( 28 ) ; /* Okay! */
if( p != NULL )/* Do something w/p ... */
free( p ) ;p = NULL ; /* No dangling ptrs */
return( 0 ) ;}
1https://goo.gl/BFyX2HKurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 12 / 21
Arrays
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 13 / 21
Introduction – Dynamically-allocated Arrays
T *a = (T*) malloc( CAP * sizeof( T )) ;
• We can maintain our own arrays, for greater flexibility• Used just the same as statically-allocated• Still must remember size, the number of things of value it stores• Must also remember capacity, how many things it can currently
store• A single value is simply an array of length one
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 14 / 21
Example – Heap Arrays
int main( void ){
int cap = 5 ;int *p = (int*) malloc( cap * sizeof( int )) ;int *t = NULL , i ;
if( p==NULL ) return( 1 ) ;
for( i=0; i<cap; ++i ) p[i] = (i+2)*3 ;
for( i=0; i<cap; ++i )printf( "*(p+%d) = %d\n", i, *(p+i) ) ;
for( t=p, i=0; i<cap; ++i, ++t )*t += 2 ; /* add 2 to each element */
free( p ) ;return( 0 ) ;
}
1https://goo.gl/zTjuPyKurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 15 / 21
Using calloc
calloc
void* calloc( size_t n, size_t size ) ;
• Takes 2 arguments• Multiplies for you• Also initialises memory
• But you won’t rely on that now
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 16 / 21
Resizing Arrays
• If array is full:• Get a larger array from the heap• Copy contents of full array over• Free old array• Update array pointer• Update capacity
• See realloc• Read through the Data Structures intro notes from CS265
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 17 / 21
Example – Resizing Arrays
int main( void ) {int *t = NULL , i, cap = 5 ;int *p = (int*) malloc( cap * sizeof( int )) ;if( p==NULL ) return( 1 ) ;
for( i=0; i<5; ++i ) p[i] = (i+2)*3 ;
/* need more space */t = (int*) malloc( cap * 2 * sizeof( int )) ;if( t==NULL ) return( 1 ) ;
for( i=0; i<cap; ++i )t[i] = p[i] ;
free( p ) ;p = t ; t = NULL ; cap *= 2 ;// ...
free( p ) ;return( 0 ) ;
}
1https://goo.gl/kXNyAGKurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 18 / 21
Using realloc
realloc
void* realloc( void* old, size_t newsize ) ;
• old is pointer to original array• newsize is the requested new size• Attempts to resize array in place
• Returns same pointer• If it can’t:
• Gets bigger chunk elsewhere• Copies contents from old• Frees old array
• Returns pointer to updated array• Return NULL if insufficient memory
• Use temporary pointer• Still have pointer to original
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 19 / 21
Recap
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 20 / 21
Notes
• Memory that is malloc’d should be free’d• Cast return from malloc• Do not assume memory was available
• malloc returns NULL when it fails• Check!
• Use sizeof operator to get size of types• free( p ) does nothing to p itself
• Simply marks memory pointed to by p as available• Don’t free same chunk twice
• Always set pointers to NULL when not using them
Kurt Schmidt (Skipjack Solutions) C Heap Memory December 13, 2021 21 / 21