c++ – Dynamic memory allocation. What doesn't get deleted on its own?


There is a code:

#include "dparser.hpp"

namespace tools {

string parseToString(const char* _fileName, const char* _needBlockName) {
   ifstream file(_fileName);

   if (!file.is_open()) {
      printf("Parser-Error-E001: Could not open file!\n");

   char          bufferString[MAX_STR_LEN];
   string        finalString;
   register bool blockIsFind =  false;

   while (file.getline(bufferString, MAX_STR_LEN)) {
      if (!blockIsFind) {
         if (!strcmp(bufferString, _needBlockName)) {
            blockIsFind = true;


      if (bufferString[0] == '#') {

      if (!bufferString[0]) {

      finalString += bufferString;

   } // end while


   if (!finalString.size()) {
      printf("GameTextData-Parser-Error-E002: Block not found!\n");

   finalString.erase(remove(finalString.begin(), finalString.end(), '"'), finalString.end());

   string::size_type charPosition = 0;

   while ((charPosition = finalString.find( "''", charPosition)) != string::npos) {
      finalString.replace(charPosition, 2, 1, '"');

   return finalString;

void parseAndPrint(const char* _fileName, const char* _needBlockName) {
   string finalString = parseToString(_fileName, _needBlockName);
   printf("%s\n", finalString.c_str());

} // end of 'namespace tools'

int main(int argc, char const *argv[]) {
   tools::parseAndPrint(argv[1], argv[2]);
   return 0;

When checked by Valgrind'ом writes:

==11211== HEAP SUMMARY:
==11211==     in use at exit: 18,944 bytes in 1 blocks
==11211==   total heap usage: 4 allocs, 3 frees, 27,511 bytes allocated
==11211== For counts of detected and suppressed errors, rerun with: -v
==11211== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

As you can see, 4 allocs и 3 frees , as far as I know, shouldn't be so. What is not deleted here and how to delete something correctly? And also one more question: are the local variables of the parseToString and parseAndPrint deleted after the completion of their functions or not?


dparser.hpp code:

#ifndef _DPARSER_HPP_
#define _DPARSER_HPP_

#include <stdio.h>
#include <fstream>
#include <cstring>
#include <algorithm>

#define MAX_STR_LEN 151

using std::string;
using std::replace;
using std::ifstream;

namespace tools {
    string parseToString(const char *data_file_name, const char *need_block_name);
    void   parseAndPrint(const char *data_file_name, const char *need_block_name);

#endif // _DPARSER_HPP_


The data that I read in a loop ( data.gtd ):

"This is ''help''!"


"This is main"


Thanks to the investigation of avp and Vlad from Moscow , I realized that local variables are deleted after the functions are executed and there is no memory leak in the program – all due to discrepancies in Valgrind versions.

Scroll to Top