So I’m learning pointers and having a difficult time identifying the memory leak here. I confess I have never used malloc() before and am new to pointer arithmetic. Thanks in advance.
/*filename: p3.c */
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buffer;
char *p;
int n;
/* allocate 10 bytes */
buffer = (char *) malloc(10);
p = buffer;
for (n=0; n<=10; n++)
*p++ = '*';
p = buffer;
for (n=0; n <=10; n++)
printf("%c ", *p++);
return 0;
}
You simply need to free your buffer by using the
free()function, when you don’t need the buffer anymore:Simply remember to balance each call to
mallocwith a call tofree, when the memory is not used anymore.The operations on your
pvariable won’t affectbuffer. They are two pointers pointing to the same area (at start), but they’re still two distinct variables. So incrementingpwon’t incrementbuffer.So nothing wrong with the pointer operations on
p, except the fact you are writing out of bounds, as stated by Daniel Fisher in the comments of your question.Also note that you should also always check for
NULL, after themalloccall, asmallocmay fail. It’s pretty rare nowadays, but if it fails, your program will probably crash, as you will then dereference aNULLpointer:The cast to
char *is not needed onmalloc, unless you are dealing with C++. In C, it’s valid to assign avoid pointerto another pointer type.