Tag: 内存泄漏

为什么不将free(p)设置为NULL?

任何原因导致这不能成为free()标准行为? 多个指针指向同一个对象: #include #include void safefree(void*& p) { free(p); p = NULL; } int main() { int *p = (int *)malloc(sizeof(int)); *p = 1234; int*& p2 = p; printf(“p=%p p2=%p\n”, p, p2); safefree((void*&)p2); printf(“p=%p p2=%p\n”, p, p2); safefree((void*&)p); // safe return 0; } 来自malloc赋值要求从void* 反之亦然: safefree()要求转换为void*& (参考)

为什么pthread导致内存泄漏

每当我创建一个pthread时,valgrind就会输出内存泄漏, 例如下面的代码: #include #include #include void *timer1_function (void *eit){ (void) eit; printf(“hello world\n”); pthread_exit(NULL); } int main(void){ pthread_t timer1; pthread_create( &timer1, NULL, timer1_function, NULL); ///////line13 int i=0; for(i=0;i<2;i++){usleep(1);} return 0; } valgrind输出 ==1395== HEAP SUMMARY: ==1395== in use at exit: 136 bytes in 1 blocks ==1395== total heap usage: 6 allocs, 5 frees, 1,134 bytes […]

如何从循环外部杀死无限循环中的pthread?

我创建了一个线程,并将其置于无限循环中。 使用valgrind检查代码时出现内存泄漏。 这是我的代码: #include #include void thread_do(void){ while(1){} } int main(){ pthread_t th; pthread_create(&th, NULL, (void *)thread_do, NULL); sleep(2); /* I want to kill thread here */ sleep(2); return 0; } 所以在main中创建一个线程,并且一直运行thread_do()。 有没有办法在2秒后从主内部杀死它? 我已经尝试过pthread_detach(th)和pthread_cancel(th)但我仍然会泄漏。

使用realloc是否安全?

前段时间,我的一位朋友告诉我不要使用realloc,因为它不安全,但他不能告诉我为什么,所以我对这个问题做了一些研究,最接近我怀疑的是: https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/809-BSI.html http://www.iso-9899.info/wiki/Why_not_realloc 我想知道我是否可以继续在我的代码中使用realloc,或者它是否不安全是否还有其他方法来重新分配内存? 感谢您的关注。

GTK hello_world计划中的内存泄漏

所以…我正试图消除我的GTK + 3程序中的一些内存泄漏。 我虽然回顾一些简单的例子看看是否有一些我忘记的清理工具是个好主意,但文档中提供的hello_world程序也有漏洞。 (下面的Valgrind输出)。 这些泄漏是否可以接受? 如果是这样,我应该使用其他一些应用来调试GTK程序吗? ==13717== Memcheck, a memory error detector ==13717== Copyright (C) 2002-2012, and GNU GPL’d, by Julian Seward et al. ==13717== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info ==13717== Command: ./a ==13717== Hello World ==13717== ==13717== HEAP SUMMARY: ==13717== in use at exit: 1,578,162 bytes in 11,614 […]

程序终止后动态分配内存

当包含动态分配的内存(使用malloc / new)而没有空闲/删除调用的C / C ++程序终止时,动态分配的内存会发生什么? 操作系统是否收回内存或者其他程序无法访问该内存?