I have read lots of programmers saying and writing when programming in C/C++ there are lots of issue related to memory. I am planning to learn to program in C/C++. I have beginner knowledge of C/C++ and I want to see some short sample why C/C++ can have issues with memory management. Please Provide some samples.
There are many ways you can corrupt or leak memory in C or C++. These errors are some of the most difficult to diagnose, because they are often not easily reproducible.
For example, it is simple to fail to free memory you have allocated. For example, this will do a "double free", trying to free a
twice and failing to free b
:
char *a = malloc(128*sizeof(char));
char *b = malloc(128*sizeof(char));
b = a;
free(a);
free(b); // will not free the pointer to the original allocated memory.
An example buffer overrun, which corrupts arbitrary memory follows. It is a buffer overrun because you do not know how long str
is. If it is longer than 256 bytes, then it will write those bytes somewhere in memory, possible overwriting your code, possibly not.
void somefunc(char *str) {
char buff[256];
strcpy(buff, str);
}