Professional Documents
Culture Documents
Memory Layout 2
Unused memory
^
|
Heap
Low Address Text Segment Read from the program file by exec.
• Returns a pointer to space for an object of size nsize or NULL if the request cannot
be satisfied.
An example
int * iptr;
iptr=(int*) malloc(sizeof(int));
*iptr=40;
• Example
free (iptr)
• After freeing the allocated memory do not use the pointer.
int main()
{
int n, i, *p, sum=0;
float avg;
printf(“How many numbers?”);
scanf(“%d”, &n);
p = (int *) malloc(n*sizeof(int));
if(p)
{
for(i=0;i<n;i++)
{
scanf(“%d”,(p+i));
sum=sum+*(p+i);
}
avg =(float)sum / n;
printf(“The average = %f”, avg);
}
else printf(“Unsuccessfull Allocation”);
}
Slide Title | CONFIDENTIAL 2006 December 8, 2021
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - calloc 7
• Example
●
Example
Suppose INITIAL_ARRAY_SIZE IS 10. Need it to increase by 5 units.
int *tmp;
/*ip is the pointer which is pointing to the old block of memory*/
/*tmp required since realloc may fail and the pointer for the old allocation may be assigned to NULL */
/*So the pointer is updated on realloc 's success*/
int f(void)
{
char * s ;
s = (char *)malloc(50 * sizeof(char)); /* get memory */
if (s==NULL)
{ return 1; /* no memory available */ }
else
{
/* memory available */
/*do something but free it before the return */
return 0; /* memory leak */
}
}
int main(void)
{ f();
return 0;
}
• Determine how much memory to be reallocated from the length of user input
– Accept elements row by row, each time, and fill the table
– Do it as a multi-file program