50 likes | 172 Vues
In this lecture, we explore dynamic memory allocation using malloc and calloc in C. We will modify Jason's ptr4.c example to allocate larger memory regions and implement printing functions. You'll learn the dangers of dynamic memory, including out-of-bounds access risks. We'll also cover binary file I/O, including writing and reading from files, and formatting output as memory dumps. Additionally, we will write programs to determine the length of binary files and manipulate file positions. This foundational knowledge is crucial for safe and effective programming in C.
E N D
CSC 253 Lecture 9
malloc and calloc • Let’s take Jason’s ptr4.c and change it • to allocate regions larger than 1 word • to incorporate a printing function like we wrote last week • to allocate something other than ints. • Let’s print the start address and ending address of each array.
Why malloc is dangerous … • If our array gets out of bounds, we can overwrite an element of another array. • How can we calculate the subscript of one array that will smash the zeroth element of the next array?
Binary file I/O • Let’s try the program for writing a file, ptr6.c. • Let’s try the program for reading a file, ptr5.c. • Let’s try to put the output in a more general format, like a memory dump.
File manipulation • Let’s write a program that determines the length of a binary file. • Let’s change the program to set the position to somewhere else in the file. • Let’s change the program to set the position to an arbitrary place in the file, and then report how far it is from the end.