如何跟踪泄漏了多少内存?
我正在做一项家庭作业,要求我编写一个泄漏内存的程序,跟踪它泄漏了多少内存,直到它崩溃。
我对该程序的总体想法是不断重新分配 malloc 指针。
到目前为止,这是我的代码:
char *oldMemory = malloc(125000); //1MB of memory.
char *newMemory = malloc(125000);
oldMemory = newMemory;
- 有没有办法将其放入循环中并重复孤立 a 一定量的内存,直到程序无法再分配任何内存并崩溃?
- 如何跟踪程序崩溃之前泄漏了多少内存?
感谢您的时间和专业知识!
I'm working on a homework assignment that requires me to write a program that leaks memory, keep track of how much memory it is leaking until it crashes.
My general thoughts for the program would be to continuously reassign a malloc pointer.
Here's my code so far:
char *oldMemory = malloc(125000); //1MB of memory.
char *newMemory = malloc(125000);
oldMemory = newMemory;
- Is there are way to put this in a loop and repeatedly orphan a
certain amount of memory until the program can no longer allocate any memory and crashes? - How can I keep track of how much memory was leaked before the program crashed?
Thanks for your time and expertise!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要忘记打印每次迭代中泄漏的大小 - 这样即使程序崩溃你也能看到结果。如果您在访问程序之前测试失败的分配,程序不应崩溃。
因此:
Linux OOM 可能会造成混乱;它允许过度使用内存。您必须在泄漏之前访问分配的内存 - 因此使用
memset()
(或者您可以使用calloc()
而不是malloc())。
Don't forget to print the size leaked on each iteration - so you see the result even if the program crashes. The program should not crash if you test for failed allocations before accessing it.
Hence:
The Linux OOM might confuse things; it allows over-commitment of memory. You'd have to access the allocated memory before leaking it - hence the
memset()
(or you could usecalloc()
instead ofmalloc()
).当你在 C 中分配一些内存块时,你应该负责使用它来释放它
free()
函数。如果您想确保您的程序不会因内存泄漏而崩溃。
当请求更多内存或使用分配的内存时,您可以使用
assert()
函数。并且您应该检查从 malloc 返回的返回指针,如果它为 NULL,则分配失败。 >>>在 Linux 内核中要小心,由于“内存过量使用”,
malloc()
永远不会返回 NULLwhen you allocate some block of memory in C you should be responsible to free it using
free()
function.if you want to make sure that your program won't crash due to some memory leaks.
you can use
assert()
function when asking for more memory or using the allocated memory.and you should check on the returned pointer returned from malloc , if it's NULL so the allocation failed. >> Be careful in linux kernels
malloc()
won't return NULL ever,due to "memory overcommit"