Pointers and memory leaks in C
ibm.com
ibm.com
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).
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.
char *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...
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.