Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIS 415 – Operating System (Lab) CIS 415 Lab 5 Valgrind (memcheck) Dave Tian.

Similar presentations


Presentation on theme: "CIS 415 – Operating System (Lab) CIS 415 Lab 5 Valgrind (memcheck) Dave Tian."— Presentation transcript:

1 CIS 415 – Operating System (Lab) CIS 415 Lab 5 Valgrind (memcheck) Dave Tian

2 Lab/Office Hour Lab: 8:00 ~ 8:50 AM Wed/Thurs Klamath 026 Office: 9:00 ~ 10:00 AM Wed/Thurs DES 224

3 Memcheck can 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

4 What we are focusing on... NAME malloc, free, calloc, realloc - Allocate and free dynamic memory SYNOPSIS #include 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

5 Mem1.c #include 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; }

6 Mem2.c #include 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(); }

7 Mem3.c #include 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); }

8 Mem4.c #include 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; }

9 Mem5.c #include int main() { char *p1 = (char *)malloc(10); char *p2 = p1 + 5; printf("p1=%p,p2=%p\n", p1, p2); free(p2); return 0; }


Download ppt "CIS 415 – Operating System (Lab) CIS 415 Lab 5 Valgrind (memcheck) Dave Tian."

Similar presentations


Ads by Google