First of all and most importantly: This is not good C++ code, not even decent. For example, some of your #includes
are wrong, like <stdio.h>
should be <cstdio>
instead. The worst thing here are those #define
s that make your code utterly unreadable. You really should read a good book on C++!
For better readability I produced the pre-processor output of your code (minus the includes of course). It looks like this:
template<class A> std::string str(A a) { std::stringstream ss; ss<<a; return ss.str(); }
template<class A, class ... B> std::string str(A a, B...b) { std::stringstream ss; ss<<a<<str(b...); return ss.str(); }
template<class A, class X>
void add(std::map<std::string,int> &m, X x, A a) { if(strncmp(a,x,(new std::string(a))->length())==0)m[a] += atoi(strchr(x,':')+1);}
template<class A, class X, class ... B>
void add(std::map<std::string,int> &m, X x, A a, B...b) { if(strncmp(a,x,(new std::string(a))->length())==0)m[a] += atoi(strchr(x,':')+1); add(m, x, b...); }
const char* name() { return str("/proc/",getpid(),"/smaps").c_str(); }
int main(int __attribute__((unused)) argc, char __attribute__((unused)) *args[])
{
char b[256];
std::map<std::string,int> m;
FILE *fp = fopen(name(), "r");
while(fgets(b, 256, fp))
add(m,b,"Rss","Shared","Private","Swap","Pss","Referenced");
for(auto it : m) { auto a = it.first; auto b = it.second;
int value = b;
fprintf(stderr, "%s: %d\n", a.c_str(), b);
}
fclose(fp);
return 1;
}
The line causing the error is
FILE *fp = fopen(name(), "r");
This is invalid because you pass a pointer to the internal buffer of the local std::string
object in name()
to fopen
. This object ceases to exist at the end of name()
, and thus the pointer does not point to valid memory anymore.
Note that you also have a memory leak in your add
methods: You new
up std::string
objects that never get deleted.
2
solved Valgrind getting strange error