PI Material for CSE 30
Total Page:16
File Type:pdf, Size:1020Kb
CSE 30: Computer Organization and Systems Programming Lecture 10: Dynamic memory allocation: A cautionary tale C struct Diba Mirza University of California, San Diego 1 Dynamic memory allocation void* realloc (void * p, size_t s); • Resize an existing block of memory pointed to by ‘p’ to a total size of ‘s’ bytes. • On failure: returns NULL on failure • Are the contents copied over to the new block? 2 Dynamic memory allocation void free(void * ptr); • Frees the heap block pointed to by p • What happens in the following code? int *p=malloc(8); free(p); free(p); 3 Dangling pointers and memory leaks – Dangling pointer: Pointer points to a memory location that no longer exists – Memory leaks (tardy free): Memory allocated by program is not freed. • The problem is particularly acute if memory allocated in heap can no longer be accessed Q: Which of the following functions returns a dangling pointer? int * f1(int num){ int *mem1 =(int *)malloc(num*sizeof(int)); return(mem1); } int * f2(int num){ int mem2[num]; return(mem2); } A. f1 B. f2 C. Both Which of the following is an example of a dangling pointer? A. void foo(int bytes) { B. int * foo(int bytes) { char *ch =(char *) malloc(bytes); int i=14; ch[0]=‘a’; . free (ch); return (&i); . } } main () { int *p = foo(10); C. char* foo(int bytes) { } char *ch =(char *) malloc(bytes); return (ch); D. A combination of the } above Memory Leak? int * createArray (int n) { int *ptr = malloc(n*sizeof(int)); return ptr; } We have a memory leak! Why? void main() { int *arr=createArray(5); } Memory Leak? int * createArray (int n) { int *ptr = malloc(size*sizeof(int)); //line 1 return ptr; } int * resizeArray (int *ptr, int n) Which of the following is true about the { given code? ptr = realloc(ptr, n*sizeof(int)); //line 2 A. There is a definite memory leak return ptr; B. There is a possible memory leak } C. There is no memory leak void main() { int *arr=createArray(5); //line 3 arr= resizeArray(arr, 10); //line 4 free(arr); } C structures : Overview • A struct is a data structure composed of simpler data types. –Like a class in Java/C++ but without methods or inheritance. struct point { int x; int y; } void PrintPoint(struct point p) { printf(“(%d,%d)”, p.x, p.y); } Pointers to structures • The C arrow operator (->) dereferences and extracts a structure field with a single operator. • The following are equivalent: struct point *p; printf(“x is %d\n”, (*p).x); printf(“x is %d\n”, p->x); Representation in memory struct p { int y; char x; }; struct p sp; sp y (4 bytes) x (1byte) 0x100 0x104 0x105.