Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 16 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
16
Dung lượng
108,54 KB
Nội dung
University of Washington Sec3on 10: Memory Alloca3on Topics ¢ Dynamic memory alloca3on § Size/number of data structures may only be known at run 7me § Need to allocate space on the heap § Need to de-‐allocate (free) unused memory so it can be re-‐allocated ¢ Implementa3on § Implicit free lists § Explicit free lists – subject of next programming assignment § Segregated free lists ¢ ¢ Garbage collec3on Common memory-‐related bugs in C programs Memory-‐Related Bugs in C University of Washington Memory-‐Related Perils and PiHalls ¢ ¢ ¢ ¢ ¢ ¢ ¢ Dereferencing bad pointers Reading unini3alized memory Overwri3ng memory Referencing nonexistent variables Freeing blocks mul3ple 3mes Referencing freed blocks Failing to free blocks Memory-‐Related Bugs in C University of Washington Dereferencing Bad Pointers ¢ The classic scanf bug int val; scanf(“%d”, val); ¢ Will cause scanf to interpret contents of val as an address! § Best case: program terminates immediately due to segmenta7on fault § Worst case: contents of val correspond to some valid read/write area of virtual memory, causing scanf to overwrite that memory, with disastrous and baffling consequences much later in program execu7on Memory-‐Related Bugs in C University of Washington Reading Unini3alized Memory ¢ Assuming that heap data is ini3alized to zero /* return y = Ax */ int *matvec(int **A, int *x) { int *y = (int *)malloc( N * sizeof(int) ); int i, j; for (i=0; i