From the course: Secure Coding in C
Unlock this course with a free trial
Join today to access over 25,600 courses taught by industry experts.
Freeing pointers - C Tutorial
From the course: Secure Coding in C
Freeing pointers
- [Instructor] In this code, the hello function accepts and outputs a string of data. The input pointer is allocated a chunk of memory. The storage is used for an input string, and then the string is output. But what's missing is freeing the buffer when the program is done using it. Therefore, the allocated memory chunk lingers in memory. Call the function too many times and you get a memory overflow. The program crashes. To fix the problem, you just need to add a single statement to the hello function. The free function deallocates memory, making it available for allocation elsewhere, especially in code where a function allocates a huge chunk of memory, and the buffer is used only within the function. Always release it before the function terminates. This code is similar to the preceding example, though all the action takes place in the main function. The memory allocated is free as was done before. Additionally, the input pointer is assigned to the null constant. By doing so, tests…