










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











Stack Top Free Space Allocated Space
#include
<malloc.h> #include
<stdio.h> int^ main(void){T^ p;p^ =^ (T)
malloc(sizeof(T)); if^ (!p)
{ exit(-1);
often
nothing
can^
do^ on
failure
} /*^ use
of^ p
not^ change p• good idea p=NULL; right after de-allocation.
/* error, p points to something not allocated */
/*runtime error, pointer is no longer valid */
/* ERROR – segmentation fault right away*/ l^ Forgetting to check return value of malloc/calloc l^ Using malloc and not initializing values–^
memset l^ Going past end of allocated space–^
very easy when using array syntax and loops *int i, myInts;myInts = (int
*) calloc(k, sizeof(int)); if (!myInts) {printf("no
memory\n"); exit(-1);} for (i=0; i <=^
k; i++)
{
myInts[i] =
anotherFunc(i,
k);
}
Goes past end of array allocated
/* ERROR: ptr does not point to something in heap */
/* ERROR: curr has already been freed */
good:
int *getInt() {int *ptr;ptr = (int *) calloc(42, sizeof(int));return ptr;} –^ -----------------------
bad:
int *getInt() {int a=7;int *ptr = &a;return ptr;}
stack
Total