5 ms·
Pointers and memory leaks in C
- galapago 12y ago> memset(p,’\0’,10);
- AlexeyBrin 12y agoI think you should read the above as: memset(p, '\0', 10); Probably best approach is to always use calloc, unless you fill the buffer yourself with other meaningful values immediately after allocation.
- dmitrygr 12y agoActually, "what bothers [...] the most about C" for me is not pointers or leaks. It is people who blame the language for their inability to keep track of the memory they allocate and use.
- yoklov 12y agoMost people who write C professionally have no trouble doing this, but memory leaks still occur. It's easy to miscommunicate what part of the code manages what memory if you're working in a group, not to mention just normal human error. It's very easy to accidentally forget to free something, especially when you're on a tight schedule or distracted. I mean, how many times have you wondered 'how did this ever work' when looking through old code you wrote? That said, most of these problems are significantly lessened by C++ (though it's obviously not a panacea).
- flohofwoe 12y agoI wonder why the link made it to the front page. Everything in there is absolutely basic knowledge which every programmer who specifically chooses C over other languages for a task knows anyway. If you choose C you know that you have to be careful about dynamic memory. Somewhat obvious, no?
- pfortuny 12y agoWell, what you say is right. However, there may well be quite a few Javascript/Java only developers around who are interested in all those funny 'memory leaks' of C.
- perlgeek 12y agoSadly it doesn't address the debugging problem at all. Mentioning very useful tools like valgrind and address sanitizer (asan), which can help to save lots of debugging time.
- larssorenson 12y agochar *name = (char *) malloc(11); // Assign some value to name memcpy ( p,name,11); // Problem begins here "In this example, the memcpy operation is trying to write 11 bytes to p, whereas it has been allocated only 10 bytes." I'm sorry, but I see it as having malloc'd 11 bytes...
- jibsen 12y agoThe first parameter to memcpy is the destination.
- wahern 12y ago"Accessing the null pointer is very dangerous, as it might crash your program. Always make sure that you are not accessing null pointers." If you're going to read or write through an invalid pointer, the NULL pointer is your friend, and an immediate segfault is the best thing that could happen. The worse thing that could happen is that the program keeps chugging along and you never notice the bug. "Always use memset along with malloc, or always use calloc" That's a good way to defeat checkers like Valgrind. I'm not saying it's a bad idea, but not something a programmer should be instinctively doing without thinking about it. In fact, excepting stylistic stuff, "always" is a poor way to approach programming. You should do nothing which isn't deliberate and well thought out.