110k views
2 votes
5. Write few lines of code that creates two arrays with malloc. Then write a statement that can create a memory leak. Discuss why you think your code has a memory leak by drawing the status of the memory after you use malloc and the line of the code you claim that creates a memory leak.

1 Answer

3 votes

Answer:

// function with memory leak

void func_to_show_mem_leak() {

int *pointer;

pointer = malloc(10 * sizeof(int));

*(pointer+3) = 99;}

// driver code

int main()

{

// Call the function

// to get the memory leak

func_to_show_mem_leak();

return 0; }

Step-by-step explanation:

Memory leakage occurs when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs by using wrong delete operator. The delete operator should be used to free a single allocated memory space, whereas the delete [] operator should be used to free an array of data values.

User Helmi
by
7.9k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.