130 likes | 302 Views
C Lab 3. C Arraylist Implementation. Goals. Review Referencing/Dereferencing Free realloc and memmove ArrayList Debugging with GDB. Review: Pointer Syntax. To get pointer to something, use ‘&’ ‘&’ allows to pass items by reference To dereference or get item pointed to use ‘*’
E N D
C Lab 3 C Arraylist Implementation
Goals • Review • Referencing/Dereferencing • Free • realloc and memmove • ArrayList • Debugging with GDB
Review: Pointer Syntax • To get pointer to something, use ‘&’ • ‘&’ allows to pass items by reference • To dereference or get item pointed to use ‘*’ • ‘*’ is the opposite of ‘&’
realloc • realloc increases the size of memory allotted to pointer • Arguments: pointer, amount of memory to allocate • Returns a void* pointer to the reallocated memory • Preserves data pointed to by original pointer • Original pointer should be set to NULL, if space is found elsewhere
Realloc and Equivalent ptr = malloc(2); ptr = realloc(ptr, 1000); ptr = malloc(2); ptr2 = malloc(1000); memcpy(ptr2, ptr, 2); free(ptr); ptr = ptr2; ptr2 = NULL; Why not: ptr = malloc(2); realloc(ptr, 1000);
Review: free • Remember to match each call to mallocwith one call to free. int *num = malloc(4) free(num); //yaaaayyy free(num); //staaahp int num = 3; free(&num); // :,O
memmove • Moves data from one memory address to another. • Provide as arguments destination and source memory addresses, as well as the number of bytes to move. • Syntax: • memmove(dest_addr, source_addr, num_bytes);
C Arraylist • Implemented as a struct with these fields: • void** buffer; • unsigned int buffer_size; • unsigned int length; • Buffer size and length are different! • Recall: access struct fields with a.length, (a is a struct), or a->length, (a is a pointer to a struct).
C Arraylist • Buffer size and length are different! • Buffer size: The maximum number of elements the array list can hold, directly related to the amount of allocated memory. • Length: The number of elements the array list actually holds. • When the array list is full, expand it by doubling the amount of memory allocated for the buffer. • Need to figure out how to detect this condition.
C Arraylist • The arraylist is a list of pointers to memory locations. • Therefore, the buffer variable is a pointer to a pointer (void** type) • We use a void** pointer so that the arraylist can be used to store variables of any type.
GDB • Gnu Project Debugger • Tool used to find errors in your code. • See C-lab 3 web page for basic commands.
#include • Preprocessor directive to include a header file in your C code. • Example: #include <stdio.h> • Performs textual inclusion (“copy-paste”). • In practice, works like import statements in java, but there are some differences behind the scenes.
Debugging with GDB • Begin the lab exercise • Where/When might realloc be useful? • Where/When might free be useful?