Skip to content

Required assistance #1400

Discussion options

You must be logged in to vote

To avoid memory leaks when using dynamically allocated memory in C++:

To avoid memory leaks when using dynamically allocated memory in C++:

1. Always pair new with delete and new[] with delete[]. For example:

int* num = new int(5); // Allocate memory
delete num; // Free memory

int* arr = new int[10]; // Allocate an array
delete[] arr; // Free the array

2. Use smart pointers like std::unique_ptr or std::shared_ptr because they automatically free the memory when no longer needed:

#include
std::unique_ptr num(new int(5)); // Automatically managed

This way, you don’t forget to release memory, and your program stays efficient and safe.

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@Vaishnavi-Ind
Comment options

@Shriharsh-Deshmukh
Comment options

@Vaishnavi-Ind
Comment options

Answer selected by Vaishnavi-Ind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants