Pointers and memory leaks in C
1–10 of 11 posts
Re: Pointers and memory leaks in C
#2Re: Pointers and memory leaks in C
#3> memset(p,’\0’,10);
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.Re: Pointers and memory leaks in C
#4Re: Pointers and memory leaks in C
#5Re: Pointers and memory leaks in C
#6Re: Pointers and memory leaks in C
#7I 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?
Re: Pointers and memory leaks in C
#8 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...
Re: Pointers and memory leaks in C
#9char *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...
Re: Pointers and memory leaks in C
#10Actually, "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.
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).