Vous êtes sur la page 1sur 14

Memory Allocation

Some Slides taken from: Alan L. Cox


Computer Science Department
Rice University
Texas
Allocation
For all data, memory must be allocated
Allocated = memory space reserved

Two questions:
When do we know the size to allocate?
When do we allocate?
Two possible answers for each:
Compile-time (static)
Run-time (dynamic)
How much memory to allocate?
Sometimes obvious:




Sometimes not:




How will these be used???
Will they point to already allocated memory (what weve seen so far)?
Will new memory need to be allocated (we havent seen this yet)?
char c;
int array[10];
One byte
10 * sizeof(int) (= 40, usually)
char *c;
int *array;
Is this going to point to one
character or a string?
How big will this array be?
malloc()





Allocate memory dynamically
Pass a size (number of bytes to allocate)
Finds unused memory that is large enough to hold the specified
number of bytes and reserves it
Returns a void * that points to the allocated memory
No typecast is needed for pointer assignment
Essentially equivalent to new in Java and C++
#include <stdlib.h>

int *array = malloc(num_items * sizeof(int));
Wont continually
remind you of this
Using malloc()






i and array are interchangeable
Arrays pointers to the initial (0th) array element
i could point to an array, as well
Allocated memory is not initialized!
calloc zeroes allocated memory (otherwise, same as
malloc; details to come in lab)
int *i;
int *array;

i = malloc(sizeof(int));
array = malloc(num_items * sizeof(int));

*i = 3;
array[3] = 5;
Statically allocates
space for 2 pointers
Dynamically
allocates space
for data
Using malloc()
Always check the return value of system calls like malloc() for errors






For brevity, wont in class
Tutorial examples will
Textbook uses capitalization convention
Capitalized version of functions are wrappers that check for errors and exit if they
occur (i.e. Malloc)
May not be appropriate to always exit on a malloc error, though, as you may be
able to recover memory
int *a = malloc(num_items * sizeof(int));
if (a == NULL) {
fprintf(stderr,Out of memory.\n);
exit(1);
}
Terminate now!
And, return 1.
When to Allocate?
Static time
Typically global variables:









Only one copy ever exists, so can
allocate at compile-time
Dynamic time
Typically local variables:









One copy exists for each call
may be unbounded # of calls, so
cant allocate at compile-time
int value;
int main(void)
{

}
int f()
{
int value;

}
int main(void)
{

}
Deallocation
Space allocated via declaration (entering scope) is deallocated when
exiting scope








Cant refer to y or array outside of f(), so their space is
deallocated upon return

You can use free() for deallocating the memory.
f(void)
{
int y;
int array[10];

}
Calloc vs Malloc
Recursion
Recursion is the process of repeating items in
a self-similar way.

Computer programming languages support
recursion by allowing a function to call itself
within the program text
Stack for recursion
Since there is no a priori limit on the depth of nested recursive calls,
we may need to save an arbitrary number of register values.

These values must be restored in the reverse of the order in which
they were saved, since in a nest of recursions the last subproblem
to be entered is the first to be finished.

This dictates the use of a stack, or ``last in, first out'' data structure,
to save register values.

We can extend the register-machine language to include a stack by
adding two kinds of instructions: Values are placed on the stack
using a save instruction and restored from the stack using a restore
instruction.

After a sequence of values has been saved on the stack, a sequence
of restores will retrieve these values in reverse order
Recursion - Example


#include<stdio.h>
main()
{
int a, fact;
printf("\nEnter any number: ");
scanf ("%d", &a);
fact=rec (a);
printf("\nFactorial Value = %d", fact);
getch();
}





rec (int x)
{
int f;
if (x==1)
{
printf("hi");
return (1);
}
else
f=x*rec(x-1);
printf("hi1");
return (f);
}

Execution Procedure
rec(2-1) = rec(1) printf("hi");
return (1); return =1// Do not
return because more values are
below
rec(3-1) f=2*rec(2-1)
rec(4-1) f=3*rec(3-1)
rec(5-1) f=4*rec(4-1)
rec(5) f=5*rec(5-1)
Thank You

Vous aimerez peut-être aussi