Lecture 8, ECE264, Spring 2012, Prof. Lu


 Feb. 2 Quiz

void f1(int * a, int * b)
{
int * c;
c = a;
a = b;
b = a;
}

int main(int argc, char * argv[])
{
int a = 12;
int b = -9;
printf(“%d %d\n”, a, b);
f1(&a,&b);
printf(“%d %d\n”, a, b);
}

In the function f1:
• c is initialized as a pointer, so it stores an address
• c stores a’s value, which is an address as called in the function
• a then stores b’s value, which is also an address.
• Nothing is changed to the actual variables in the main function so the output is still 12 -9
• Since none of the assignments in f1 pass-by-address, all of the values in f1 stay in f1 and none of the values change outside of f1. Therefore the values in the main function are not changed.
• The assignment c = *a; would be incorrect since *a is an integer while c is a pointer

Heap Memory

In heap memory, you have less control unlike stack memory.
Stack Memory: first in → last out
Heap Memory: random access
However, it means that you need to allocate and release. You need to do more work with heap.
Stack memory is smaller than heap memory (depending on OS).

int arr[100];
arr[5] = 8;
arr[34] = -9;
...
int y = arr[17];
/*elements not initialized*/

The philosophy of C is to do a minimal amount of work for the program to work faster. As a result, the programmer must take responsibility for crashes and errors.

int * arr2;
...
arr2 = malloc(num * sizeof(int));
free(arr2);

In the code above, arr2 is allocated in heap memory.
Once you know the amount of memory you require, you can use malloc to allocate memory for your array. If you run out of memory, the variable will return NULL.
Once you don’t need the memory anymore, you must free the memory.
The variable at stack memory will stay there until the function returns. The variable at heap memory will be removed once you free the memory.

In 2-dimensional arrays, you must allocate in two steps.

int ** arr2d = NULL;
/* create first dimension (rows)*/
arr2d = malloc(numRow * sizeof(int *));
if (arr2d == NULL)...
for (c = 0; c < numCol; c++)
{
arr2d[c] = malloc(numCol * sizeof(int));
}
/* now you can use arr2d[row][column] */
...
for (c = 0; c < numCol; c++)
{
free(arr2d[c]);
}
free(arr2d); /* malloc first, free last */

Heap memory is a very very large piece of memory. When you call malloc, it gives you a piece of that memory.
The first dimension of the array is an array of pointers.
The second dimension is the array of integers.
You must release the integers; then release the pointers. Do it in reverse order of malloc.
Basically, you are creating two one-dimensional arrays.


Back to ECE264, Spring 2012, Prof. Lu

Alumni Liaison

Questions/answers with a recent ECE grad

Ryne Rayburn