113 shared variables in threaded programs 571

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: following example: 1 2 3 4 5 6 int *stackref () { int val; return &val; } This function returns a pointer (say p) to a local variable on the stack and then pops its stack frame. Although p still points to a valid memory address, it no longer points to a valid variable. When other functions are called later in the program, the memory will be reused for their stack frames. Later, if the program assigns some value to *p, then it might actually be modifying an entry in another function’s stack frame, with potentially disastrous and baffling consequences. 10.11. COMMON MEMORY-RELATED BUGS IN C PROGRAMS 555 10.11.9 Referencing Data in Free Heap Blocks A similar error is to reference data in heap blocks that have already been freed. For example, consider the following example, which allocates an integer array x in line 6, prematurely frees block x in line 12, and then later references it in line 14. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 int *heapref(int n, int m) { int i; int *x, *y; x = (int *)Malloc(n * sizeof(int)); /* ... */ free(x); y = (int *)Mal...
View Full Document

This note was uploaded on 09/02/2010 for the course ELECTRICAL 360 taught by Professor Schultz during the Spring '10 term at BYU.

Ask a homework question - tutors are online