简体   繁体   中英

can i track dynamic memory?

In many cases we declare a pointer dynamically in a function, and sometimes we don't want to free that memory at the return of the function, because we need that memory later.

We can return that dynamic pointer and later free it. I found some way to track that memory. Is that a good thing:

#include <iostream>

int foo()
{
    int* pInt = new int(77);
    int x = (int)pInt;
    std::cout << std::hex << x << std::endl; // 3831d8
    return x;
}


int main()
{

    int* pLostMem = (int*)foo();

    std::cout <<  pLostMem << std::endl; // 003831D8
    std::cout << std::dec << *pLostMem << std::endl; // 77 

    if(pLostMem)
    {
        delete pLostMem;
        pLostMem = NULL;
    }

    std::cout << std::endl;
    return 0;
}

It's not entirely clear in your question, but if you just want to add cout statements to your code to show the value of a pointer, you can do that without casting to int . Pointers can be printed just fine:

#include <iostream>

int *foo()
{
  int* pInt = new int(77);
  std::cout << pInt << std::endl; // pointers can be output just fine
  return pInt;
}

int main()
{
  int* pLostMem = foo();

  std::cout << pLostMem << std::endl; // e.g. 0x16c2010
  std::cout << *pLostMem << std::endl; // 77

  delete pLostMem;
  pLostMem = NULL;

  std::cout << std::endl;
  return 0;
}

Live example here.

You also don't need the if (pLostMem==NULL) check before deleting.

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