简体   繁体   中英

Can c++ array also leak memory?

I am new to c++, I was fearlessly experimenting until I saw the lecture on cs50 that memory leaks and this other stuff can crash my computer, I have programmed in PHP and javascript, where such things don't exist I guess, here is the program I wrote:

int main(int argc, char** argv) {

    ifstream inFile;

ofstream outFile;

int size;

inFile.open("text.txt"); //Step 2

outFile.open("formated.out"); //Step 3

// here I am sending the file through PHP where the first line of the file is the number of lines in the file

inFile >> size;

size += 1;

string strArr[size];

for(int i = 0;i < size;i++){
    getline(inFile, strArr[i]);
}

string crntStr;
int sl;
string newStr;
for(int i = 1;i < size;i++){

    newStr = "";

    string crntStr = strArr[i];

    sl = crntStr.length();

    for(int j = 0;j < sl;j++){

        if(crntStr[j] == '<')
        newStr += "&lt;";
        else if(crntStr[j] == '>')
        newStr += "&gt;";
        else
        newStr += crntStr[j];

    }

    cout << newStr  << endl; 

    if(i != (size - 1))
    cout <<  "<br>";

}

    return 0;
}

My question is when I write a program of this sort should I be afraid of memory leaks, I compiled this program in devc++ and it was working fine but when I went to visual studio I got the following error: c:\\users\\hamza\\source\\repos\\hypertextformatting\\hypertextformatting\\hypertextformatting.cpp(32): error C2131: expression did not evaluate to a constant c:\\users\\hamza\\source\\repos\\hypertextformatting\\hypertextformatting\\hypertextformatting.cpp(32): note: failure was caused by a read of a variable outside its lifetime c:\\users\\hamza\\source\\repos\\hypertextformatting\\hypertextformatting\\hypertextformatting.cpp(32): note: see usage of 'size'

Only memory allocation on the heap (or dynamic allocation) can lead to memory leaks. When you declare an array string strArr[size]; it will be placed on the stack and will be automatically "released" when program leaves current scope (stack pointer will decrease by strArr size) and desctructor will be called. Although the "string" objects data placed in dynamically alocated memory, it will be released by destructors. Memory leak is impossible here. You can create a memory leak if you allocate memory in a heap by new, new[], malloc etc. call and forget to release the data after they are no longer needed.

So

string strArr[size]; // no leaks
string* strArr = new string[size]; //may be leak if you forget call delete[] strArr

Besides, variable length arrays is non-standard in C++ avoid using it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM