CSE 333 Section BB Logistics Due Friday: Exercise 4 @ 11 am NO - - PowerPoint PPT Presentation
CSE 333 Section BB Logistics Due Friday: Exercise 4 @ 11 am NO - - PowerPoint PPT Presentation
CSE 333 Section BB Logistics Due Friday: Exercise 4 @ 11 am NO SCHOOL MONDAY Due Wednesday: Exercise 5 @ 11 am Exercise 6@ 11 am Due in 1 Week: (1/23) HW1 @11:59 pm Defining Structs Defining Structs Defining Structs Similar syntax to:
Logistics
Due Friday: Exercise 4 @ 11 am NO SCHOOL MONDAY Due Wednesday: Exercise 5 @ 11 am Exercise 6@ 11 am Due in 1 Week: (1/23) HW1 @11:59 pm
Defining Structs
Defining Structs
Defining Structs
int x, *y; Similar syntax to:
Struct Memory diagrams
Fruits & Orchards
main bt name
- rigin
volume apple "Apple Orchard\0" applePtr console output
8
"Apple Orchard\0" main "Eaten Fruit Orchard\0" bt name
- rigin
volume apple applePtr console output eatFruit
- rigin
volume apple
9
"Apple Orchard\0" main "Eaten Fruit Orchard\0" bt name
- rigin
volume apple applePtr console output growFruit fruitPtr
10
"Apple Orchard\0" main "Eaten Fruit Orchard\0" bt name
- rigin
volume apple applePtr console output exchangeFruit fruitPtrPtr banana Heap Allocated Memory name
- rigin
volume 12 "Banana Orchard"
11
"Apple Orchard\0" main "Eaten Fruit Orchard\0" bt name
- rigin
volume apple applePtr console output exchangeFruit fruitPtrPtr banana Heap Allocated Memory name
- rigin
volume 12 "Banana Orchard" growFruit fruitPtr eatFruit
- rigin
volume apple
12
Valgrind
- ○
./leaky 1 10
- valgrind --leak-check=full ./leaky 1 10”
int* rangeArray(
int n, int m) {
int length = m - n + 1; // Heap allocate the array needed to return int *array = (int*)malloc(sizeof(int) * length); // Initialize the elements for (int i = 0; i <= length; i++) { array[i] = i + n; } return array; }
int main(int argc, char *argv[]) { if (argc != 3) return EXIT_FAILURE ; // Parse cmd-line args int n = atoi(argv[1]), m = atoi(argv[2]); int *nums = rangeArray(n, m); // Print the resulting array for (int i = 0; i <= (m - n + 1); i++) { printf("%d", nums[i]); } // Append newline char to our output puts(""); return EXIT_SUCCESS ; }
14
int* rangeArray(
int n, int m) {
int length = m - n + 1; // Heap allocate the array needed to return int *array = (int*)malloc(sizeof(int) * length); // Initialize the elements // By using <=, we are writing to length + 1 // ints instead of length ints // Change <= to < to fix this off-by-one error for (int i = 0; i < length; i++) { array[i] = i + n; } return array; }
int main(int argc, char *argv[]) { if (argc != 3) return EXIT_FAILURE ; // Parse cmd-line args int n = atoi(argv[1]), m = atoi(argv[2]); int *nums = rangeArray(n, m); // Print the resulting array // We’re allocating space for 10 ints, but we access // 11 ints with i <= instead of i < for (int i = 0; i < (m - n + 1); i++) { printf("%d", nums[i]); } // We need to free the array of integers // malloced in rangeArray. free(nums); // Append newline char to our output puts(""); return EXIT_SUCCESS ; }
15