lecture 10: dynamic memory allocation: a … 30: computer organization and systems programming...
TRANSCRIPT
CSE 30: Computer Organization and Systems Programming
Lecture 10: Dynamic memory allocation:
A cautionary taleC struct
Diba MirzaUniversity 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);
}
A. f1
B. f2
C. Both
int * f2(int num){int mem2[num];return(mem2);}
Which of the following is an example of a dangling pointer?
A. void foo(int bytes) {char *ch =(char *) malloc(bytes);ch[0]=‘a’;free (ch);. . . .
}
B. int * foo(int bytes) {int i=14;. . . .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;
}
void main() {
int *arr=createArray(5);
}
We have a memory leak! Why?
Memory Leak?int * createArray (int n)
{
int *ptr = malloc(size*sizeof(int)); //line 1
return ptr;
}
int * resizeArray (int *ptr, int n)
{
ptr = realloc(ptr, n*sizeof(int)); //line 2
return ptr;
}
void main() {
int *arr=createArray(5); //line 3
arr= resizeArray(arr, 10); //line 4
free(arr);
}
Which of the following is true about the given code?A. There is a definite memory leak B. There is a possible memory leakC. There is no memory leak
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 memorystruct p {
int y;
char x;};
struct p sp;
x (1byte)y (4 bytes)
sp
0x100 0x104 0x105