AND CORRECT ANSWERS
How do you create an array dynamically? - CORRECT ANSWER int *numbers = malloc(size *
sizeof(int) );
Free(numbers);
- Dynamically allocated data is stored on the heap
How do you create an array statically? - CORRECT ANSWER char buffer[100] = {0};
- Statically allocated data is created on the run-time stack
How do you free a dynamically allocated array? - CORRECT ANSWER free(numbers);
What does free do, or not do, to a pointer after it is called? - CORRECT ANSWER - free
returns the memory that was assigned to a pointer back to the system.
- free may only be used on pointers that have been allocated using malloc and friends.
- free may only be used 1 time on a pointer.
- free does not automatically reset the pointer to NULL
- After using free the pointer is still a variable and can be reused, assuming you allocate it new
memory
- You should always NULL out a pointer after you free it.
What is the [ ] notation really doing? - CORRECT ANSWER Array names are essentially
constant pointers- meaning only the address of the first element is stored- and the location of the array
elements may not be moved...it's constant
Array[0] = 10; //is the same as
*(array+0) = 10;
What is a memory leak? - CORRECT ANSWER - A memory leak occurs when memory is
allocated but never deallocated.
- When memory is allocated, be sure to deallocate it.
, - For example, if a function creates an array and returns it to another function, that second function is
responsible for cleaning the memory.
What tool do we use to help detect memory leaks? - CORRECT ANSWER Valgrind is a tool
that can help find memory issues.
How do you use realloc and what is it used for? - CORRECT ANSWER - realloc will attempt to
resize the current memory to the requested size.
- If it can do so in the same memory location now memory is moved
- If it cannot, then realloc will:
1. Allocate new memory of the requested size somewhere else,
2. Copy the existing memory into the new memory,
3. Release the old memory, and
4. Return a pointer to the new memory
How can consts be used with pointers?
- const targets
- const pointers
- all const - CORRECT ANSWER Can be used in 4 different ways:
1. No const
Int *ptr; //ptr is a pointer to an int. Both can be changed
2. Constant pointer
Int * const ptr; //ptr is a constant pointer to an int.//ptr cannot be changed. Target can be.
3. Constant target
Const int *ptr; //ptr is a pointer to an int constant//ptr can be pointed to a new target, but target cannot
be changed
4. Constant pointer and target
Const int * const ptr;//ptr is a constant pointer to a constant int.//all is contant and cannot be chagned.
What is pointer casting? - CORRECT ANSWER Casting a pointer to a pointer of a different
size can yield in different amounts of data being dereferenced.
- For example,