Memory Flashcards

1
Q

In general how does a stack work at initial run time?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a stack frame/activation record and how/what information is stored?

A

It stores:

  • parameters
  • local variables
  • return address
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do array pointers work? How are they assigned and accessed?

A
  1. Array pointers can point to the array name(and work like the original array)
  2. 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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Array’s do not know their own size, how can you determine the size of an array?

A

int a[17];

n = sizeof(a)/sizeof(a[0]);//would give size of array

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the heap?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does malloc work? How is it initialized?

A
  1. 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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is calloc and how is it different from malloc? How do you initialize it?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you return a heap array using malloc?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you create a dynamically allocated string and array?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly