glibc malloc()字节总数
Total glibc malloc() bytes
如何获得程序中malloc()'d的总字节数(假设我使用glibc运行)?我不想看到程序占用了多少内存,我想看到我分配了多少内存。下面是一个示例程序,其中这些数字将非常不同。
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main() {
vector<void *> p;
printf("Allocating...n");
for (size_t i = 0; i < 1024 * 1024 * 10; ++i) {
p.push_back(malloc(1024));
memset(*p.rbegin(), 0, 1024);
}
printf("Press return to continue...n");
getchar();
printf("Freeing all but last...n");
for (size_t i = 0; i < p.size() - 1; ++i)
free(p[i]);
printf("Press return to continue...n");
getchar();
// UNTIL THIS FREE, TOP WOULD SHOW THIS PROGRAM TAKES 16G,
// BUT THE TOTAL MALLOC() SIZE IS MUCH LESS.
printf("Freeing last...n");
free(*p.rbegin());
printf("Press return to continue...n");
getchar();
}
我知道这可以通过LD_PRELOAD或通过拥有自己的malloc
和free
函数来实现,但是是否有更简单的方法来获得malloc()
总数?
各种语言标准规定:
没有独立于平台的方法来获取这些信息。malloc的不同实现可能提供此信息,但它将以非标准的方式提供。
Glibc提供:
-
您可以使用
__malloc_hook
特性来编写一个钩子,该钩子计算已分配的内存数量。 -
还有
mallinfo()
,它应该提供一些关于已分配内存的信息。
创建一个全局变量和自己的malloc()
函数
static size_t count;
void *malloc_ex(size_t n)
{
count+=n;
return malloc(n);
}
那么任何时候你都可以通过查看count
变量来知道分配了多少字节。
全局变量被编译器初始化为0,所以没有问题。并且请不要将#undef
malloc
和#define
更改为malloc_ex()
,否则将为未定义行为。
您应该定义两个函数,并分配额外的空间来跟踪每次调用自定义分配器函数所分配的内存。
//Space to store the size of an allocation
struct _room {
size_t sz; //Chunk size
char padding[16-(sizeof(size_t) % 16)]; //Force 16-byte alignment
}
//A global variable to keep track of the total amount of memory allocated (except the extra space of storing chunk sizes
static size_t TOTAL = 0;
//Custom allocator
void *mymalloc(size_t sz) {
//Allocate memory plus room for storing the chunk size. We'll need it later in
//myfree() to appropriately decrement TOTAL.
struct _room *r = (struct _room *) malloc(sz + sizeof(struct _room));
r->sz = sz;
TOTAL += sz; //keep track of user allocated memory
return (void *) (r+1); //Pointer to usable memory
}
void myfree(void *m) {
//Point to the register with chunk size, given the memory pointer returned my mymalloc()
struct _room *r = ((struct _room *) m) - 1;
TOTAL -= r->sz; //Update total
free((void*)r); //Free all memory: room + user memory
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 如果没有malloc,链表实现将失败
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 在UNIX系统中使用DIR查找文件的字节大小
- malloc() 可能出现内存泄漏
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- std::当在256字节边界上写入整数时,流的奇怪行为
- 当比特(而不是字节)的顺序至关重要时的持久性
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 字节到位运算符重载C++
- 在java中读取c++字节的位字段
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- 如果Malloc无法分配X字节,我应该使用Realloc还是再次使用Malloc?C++
- 小于 8 个字节的 malloc
- glibc malloc()字节总数
- 如果我对浮点变量使用malloc和calloc,并将其赋值为int,那么剩下的2个字节会发生什么呢?
- 为什么两个malloc之间有一行额外的8字节