Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Memory – A Review

Similar presentations


Presentation on theme: "Dynamic Memory – A Review"— Presentation transcript:

1 Dynamic Memory – A Review
Adapted from Dr. Mary Eberlein, UT Austin

2 Dynamic Memory We can allocate memory on the heap during program execution Often used for strings, arrays, structs, linked lists, trees <stdlib.h> declares 3 memory allocation functions: malloc: allocates an uninitialized block of memory calloc: allocates a block of memory and initializes to zero Takes time to zero out memory – don't use unless needed realloc: resizes allocated block of memory All three return type void * (a void pointer) Return null pointer if block of requested size isn't found NULL represents null pointer

3 Allocating Memory prototype: void *malloc(size_t size);
malloc allocates contiguous size bytes and returns pointer to it size_t: unsigned integer type (defined in <stdlib.h>) void free(void *ptr); // free memory when done with it Example: array of n ints int * a = malloc(n * sizeof(int));// a holds address of first elt if(a != NULL) { // better: if(a) for(int i = 0; i < n; i++) a[i] = i; // Or: *(a+i) = i; } Later - free memory: free(a);

4 Deallocation & Common Mistakes
free(a); // releases allocated block on heap Free memory which has been dynamically allocated Calling free() does not change value of pointer variable – reset it to NULL Common mistakes: dangling pointer: a pointer that contains the address of dynamic memory which has been freed Can happen when there are multiple pointers to dynamically allocated memory memory leak: memory is allocated and not freed up again system will eventually run out of memory can occur if memory is malloc'ed in a loop check return value of malloc/calloc/realloc to ensure it isn't NULL use valgrind to detect (more on valgrind in recitation) double deallocation: attempting to deallocate memory pointed to by dangling pointer uninitialized pointer: an uninitialized pointer contains garbage – trying to access random memory location can cause unpredictable behavior

5 Memory Leak p = malloc(...); q = malloc(...); p = q;
no pointer to 1st block (garbage) Block cannot be freed This sort of code leads to memory leaks

6 Dangling Pointer char *ptr1 = malloc(10*sizeof(char)); // new string char *ptr2 = ptr1; ... free(ptr2); strcpy(ptr1, "hello"); Two dangling pointers – point to same deallocated memory

7 String Functions char *myConcat(const char *s1, const char *s2) {
char *result = malloc(strlen(s1) + strlen(s2) + 1); if(result == NULL) { printf("Error: malloc failed\n"); exit(EXIT_FAILURE); } strcpy(result, s1); strcat(result, s2); return result; Function call: char *p = myConcat("hello ", "world"); process termination: flushes output streams, closes open streams Type man 3 exit at command prompt for more info version of strcat: takes pointers to two strings, allocates enough memory for both + the null character, allocates memory for concatenated string and copies both strings in

8 calloc Prototype: void *calloc(size_t nmemb, size_t size);
Allocates space for nmemb elements, each of size bytes Initializes memory to 0 Performance hit for initialization – don't use unless you really need initialization to 0

9 Dynamically Allocated Arrays
Particularly useful before C99 standard allowed non-constant array sizes int numVals = -1; double *data = NULL; do { printf("How many data values do you want to store? "); scanf("%d", &numVals); } while (numVals < 1); data = malloc(numVals * sizeof(double)); // uninitialized // data = calloc(numValues, sizeof(double)); // cleared to zeros if(!data) printf("Error – malloc failed\n");

10 realloc Resize a dynamically allocated array
Prototype: void *realloc(void *ptr, size_t size); ptr points to previously allocated memory block if ptr is NULL, new block allocated and pointer to block returned size = new size of block in bytes (can be larger or smaller than original size) if size is 0 and ptr points to existing block, block is deallocated and NULL is returned Returns pointer to new block or NULL on failure Attempts to use original block of memory, shrinking or expanding it in place int *temp = realloc(ptr, 1000 * sizeof(int)); if(temp) ptr = temp; Check for success of realloc call before resetting pointer to data


Download ppt "Dynamic Memory – A Review"

Similar presentations


Ads by Google