The malloc() function allocates a chunk of memory, which is saved in a pointer variable. To ensure that malloc() allocated memory, compare the return value with the NULL pointer constant, which is returned when the allocation fails. The malloc() function requires an argument equal to the amount of memory requested. Use the sizeof operator to calculate the proper storage based on the storage buffer's data type. When you're done using an allocated chunk of memory, use the free() function to de-allocate it.
- [Instructor] When you need a chunk of memory … on the fly, you allocate storage for a new buffer … by using a pointer. … In this exercise file, … a storage buffer for 128 characters is created … as the program runs. … Two key statements make this possible. … First, a character pointer variable buffer … is declared at line six. … Second, the malloc function at line eight … allocates a chunk of 128 bytes … of memory to use as that buffer, … build and run. … Now you don't see the buffer in the output … but it was successfully created … because an error message did not appear. … The malloc function allocates memory … which is where it gets its name, memory allocation. … It requires an argument equal … to the quantity of memory desired, … measured in bytes, what's called a size_t data type … which is essentially a character. … The value returned is a memory location upon success … or the null constant on failure. … The malloc function is prototyped in the stdlib header file … which must be included in your source code. …
- Working with arrays
- Building a structure
- Creating an array of structures
- Testing characters
- Working with strings in C
- Using pointers to manipulate data
- Manipulating files
- Using command-line arguments
- Working with time functions
Skill Level Intermediate
1. Arrays and Structures
2. Characters and Strings
4. Files and the Operating System
5. The Interesting and Extraordinary
Next steps1m 52s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.