Memory Flashcards
In general how does a stack work at initial run time?
What is a stack frame/activation record and how/what information is stored?
It stores:
- parameters
- local variables
- return address
How do array pointers work? How are they assigned and accessed?
- Array pointers can point to the array name(and work like the original array)
- Array pointers can point to an array’s index and that pointer would treat that as the 0 index and enumerate from there.
int a[5] = {10,20,30,40};
int* p1 = &a[1];
*p1 = 100; //(would change 20 to 100)
*p1[1] = 200; //(would change 30 to 200)
Array’s do not know their own size, how can you determine the size of an array?
int a[17];
n = sizeof(a)/sizeof(a[0]);//would give size of array
What is the heap?
- The heap is a large pool of unuesed memory that you canuse for dynamically allocating data
- it is allocated/deallocated explicity, not(like the stack) on function calls/returns
How does malloc work? How is it initialized?
- malloc function allocates a heap memory block of a given size
- returns a pointer to the first byte of memory
- can/should cast the returned point to the appropriate type
- initially the memory contains garbage data
- often use with sizeof to allocate memory for a given data type
2.
int* a[] = (int*)malloc(8 * (size of(int));
a[0] = 10;
a[1] = 20;
What is calloc and how is it different from malloc? How do you initialize it?
- calloc is like malloc, but it zero’s out the memory(instead of leaving it)
- it also takes two parameters, number of elements and size of each
- it is preferred over malloc for avoiding bugs (but is slightly slower)
int* a = (int*)calloc(8, sizeof(int));
How do you return a heap array using malloc?
int main(){
int nums[4] = {7,4,3,5};
}
int* copy(int a[], int size){
int i;
int* a2 = malloc(size * sizeof(int));
for(int i = 0; i< size; i++){
a2[i] = a[i];
}
return a2;
}
How do you create a dynamically allocated string and array?
For String
char * p;
p = (char *) malloc(n+1);
For Array
int * a;
a = (int*)malloc(n * sizeof(int)); //n is whatever the size of the array would be.