Class 15: Pointers Continued Flashcards
Pointer to void
Void *ptr
A pointer to void is a general purpose pointer used to hold references to ANY dATA TYPE
Any pointer can be assigned to a pointer to void. It can then BE CAST BACK to its original data type
Void *ptr;
Int in_var = 5;
ptr = &int_var;
Float+ptr = ptr;
Float_ptr = (float)&int_var
Valid
A pointer to void cannot be _____ without CASTING because compiler wont know how to interpret the data the pointer points to since it does not have a data type
Deferenced
Dynamic allocation = _____ allocation
Runtime
What does Malloc?
Returns a pointer to void (void *) which points to the address of the first byte of the allocated memory space on the heap
What does callow return?
Callow returns a pointer to void which points to the address of the first byte of the allocated memory space
Parameters for calloc
Two parameters, number of elements for which storage is being requested and we of each element in bytes
Int *p;
P = calloc(4,sizeof(int));
What do malloc and calloc return if memory allocation fails?
Returns the NULL pointer which has a value of 0.
Before accessing allocated memory what should you check for
Make sure the pointer does not point to NULL
What function is used to free dynamically allocated memory
Free()
What should the pointer being passed into free be set to to ensure you do not attempt to access it
Should be set to NULL or 0
1st common error in memory allocation
NOT checking for allocation faliures
2nd common error in memory allocation
Not deallocating memory
Logical errors
All allocations must follow the same patter, allocation using malloc(), usage to store data, deallocation suing free. Failure to adhere to this pattern such as memory usage after call to free() (dangling pointer) or before a call to malloc() (wild pointer), calling free() TWICE (“double free”) usually causes segmentation fault and results in crash of program.
If malloc() and calloc() point to first byte in allocated memory, how to access the rest of the space beyond first element?
Pointer arithmetic
If you want to modify a pointer, what should you pass to function
Should pass the address of the pointer
If you pass by value a pointer to function and modify the data that the pointer points to, will the data change outside the function
Yes
The malloc() function initialized the allocated memory to 0
False, malloc() does not initialize memory to zero. It allocates initialized memory which may contain garbage values. Use calloc() for zero-initialized memory.
How can we access array[i] using pointers?
*(array + i)
*p + 3 = 45
*(p+3) = 45
The first one is invalid because the L-value of an assignment operator should be a location in memory where the value can be stored and the R value should be a numerical value that can be stored in binary form. However *p + 3 is not a valid expression for an L-value