90 likes | 227 Views
CIS 415 Lab 5 Valgrind (memcheck) Dave Tian. CIS 415 – Operating System (Lab). Lab/Office Hour. Lab: 8:00 ~ 8:50 AM Wed/Thurs Klamath 026 Office: 9:00 ~ 10:00 AM Wed/Thurs DES 224 daveti@cs.uoregon.edu. Memcheck can. 1. Use of uninitialized memory
E N D
CIS 415 Lab 5 Valgrind (memcheck) Dave Tian CIS 415 – Operating System (Lab)
Lab/Office Hour Lab: 8:00 ~ 8:50 AM Wed/Thurs Klamath 026 Office: 9:00 ~ 10:00 AM Wed/Thurs DES 224 daveti@cs.uoregon.edu
Memcheck can... 1. Use of uninitialized memory 2. Reading/writing memory after it has been free'd 3. Reading/writing off the end of malloc'd blocks 4. Reading/writing inappropriate areas on the stack 5. Memory leaks -- where pointers to malloc'd blocks are lost forever 6. Mismatched use of malloc/new/new [] vs free/delete/delete [] 7. Overlapping src and dst pointers in memcpy() and related functions 8. Some misuses of the POSIX pthreads API
What we are focusing on... NAME malloc, free, calloc, realloc - Allocate and free dynamic memory SYNOPSIS #include <stdlib.h> void *malloc(size_t size); void free(void *ptr); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size); Gcc -o myBadProgram -g memX.c Valgrind --tool=memcheck --leak-check=yes --show-reachables=yes ./myBadProgram
Mem1.c #include <stdio.h> int main() { char *p; // Allocation #1 of 19 bytes p = (char *) malloc(19); // Allocation #2 of 12 bytes p = (char *) malloc(12); free(p); // Allocation #3 of 16 bytes p = (char *) malloc(16); return 0; }
Mem2.c #include <stdlib.h> #include <stdio.h> void get_mem() { char *ptr; ptr = (char *) malloc (10); /* memory not freed */ } int main(void) { int i; char *ptr1, *ptr2; ptr1 = (char *) malloc (512); ptr2 = (char *) malloc (512); ptr2 = ptr1; /* causes the memory leak of ptr1 */ free(ptr2); free(ptr1); for ( i = 0; i < 512; i++ ) { get_mem(); } }
Mem3.c #include <stdlib.h> #include <stdio.h> int main(void) { char *chptr; char *chptr1; int i = 1; chptr = (char *) malloc(512); chptr1 = (char *) malloc (512); for ( i; i <= 513; i++ ) { chptr[i] = '?'; /* error when i = 513 invalid write */ chptr1[i] = chptr[i]; /* error when i = 513 invalid read and write */ } free(chptr1); free(chptr); }
Mem4.c #include <stdio.h> #include <stdlib.h> void initialize(int *array, int size) { int i; for (i = 0; i <= size; ++i) array[i] = 0; } int main(void) { int *p = malloc(sizeof(int)); int values[10]; *p = 37; initialize(values, 10); printf("*p = %d\n", *p); free(p); return 0; }
Mem5.c #include <stdio.h> #include <stdlib.h> int main() { char *p1 = (char *)malloc(10); char *p2 = p1 + 5; printf("p1=%p,p2=%p\n", p1, p2); free(p2); return 0; }