Minuteman
Minuteman

Reputation: 73

Is there any memory leak in this code?

#include <iostream>

using namespace std;

int main()
{
    int i,j;
    int * k;
    char m;
    do{
        cin >> j;
        k = new int[j];
        for (i = 0; i < j; i++){
            k[i] = i;
            cout << k[i] << ", ";
        }

        delete[] k;

        cout << "\nContinue?\n";
        cin >> m;
    }while (m != 'n');
}

This is a program I made to describe my problem in understanding new and delete. Will 'k' produce memory leak?

Upvotes: 0

Views: 142

Answers (3)

learnvst
learnvst

Reputation: 16195

No, it will not in this instance as you free the memory within the loop. However, you'd be much better of using a scoped_array in this instance.

Upvotes: 0

MeloMCR
MeloMCR

Reputation: 412

As already pointed out by sharptooth, you should use a try-catch block to make sure any exception is caught and k is released. In a general case, you can use valgrind to check if your program is freeing all blocks that were allocated during execution.

Upvotes: 1

sharptooth
sharptooth

Reputation: 170469

This code is not exception safe - if an exception is thrown between new[] and delete[] the block pointed to is leaked. Use std::vector to resolve this problem.

Upvotes: 11

Related Questions