I am writing application on c++ and using intel inspector to do memory profiling.
However i have a question about the various results that i got during my memory profiling test for finding potential memory problems.
I am trying to do a better stable application and i have few questions I know they are basics still at this time looking too much into the code i am kind of confused. Thank you for the help in getting them clarfied.
One instance is In my caller class constructor i have initialized the handle as
m_hidHandle = NULL; //member variable and an object of struct hid_device
After which i make a call to do hid_write.
And in there, hid_write which inturns calls writeFile (this is the api class hid.c)
WriteFile(dev->device_handle, buf, length, NULL, NULL);
Here i get a complain that uninitialized memory access. I even tried checking the api documentation for WrtieFile. Still unclean what i am making it to complain about a memory problem.
Another instance is I have a member variable
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG m_pConfig;
In the constructor, I am trying to initialize the struct to NULL:
memset( &m_pConfig, 0, sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG) );
It complained uninitialized memory access. I even tried
//proxyConfig.fAutoDetect = false;
//proxyConfig.lpszAutoConfigUrl = NULL;
//proxyConfig.lpszProxy = NULL;
//proxyConfig.lpszProxyBypass = NULL;
Still no help.
1: Use std::string
and it will be default-initialized:
std::string s; //empty
Otherwise, char s[30] = {};
will fill it with 0s. std::string
is much, much better for a stable application. If you need the C string to pass to an API, use c_str()
to get a constant version. If you need a non-constant version, plop it into a vector of characters (which can be initialized with two iterators) and pass either &v[0]
or v.data()
.
2: NULL
should work, as it's a wchar_t *
(assuming the Windows API data type). If you have C++11, use nullptr
instead.
3: memset
is a terrible idea for any non-POD class. If you don't have a constructor, a default constructor will be provided for you that default-initializes all of the non-trivially constructible members. It's better to put in your own if you have members such as int
, which would otherwise remain uninitialized:
struct S {
int i;
std::string s; //non-trivially constructible, so default-initialized
};
S s;
In the above example, you'll get an empty string and uninitialized int
. That's why your own is usually better:
S() : i(), s() {}
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.