I was looking at an example here: https://blog.parasoft.com/finding-memory-leaks-in-c

#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *string, *string_so_far;
    int i, length;     length = 0;
    for(i=0; i<argc; i++) {
        length += strlen(argv[i])+1;
        string = malloc(length+1);

        /*  * Copy the string built so far. */
        if(string_so_far != (char *)0)
            strcpy(string, string_so_far);
        else *string = '\0';
        strcat(string, argv[i]);
        if(i < argc-1) strcat(string, " ");
        string_so_far = string;
    printf("You entered: %s\n", string_so_far);
    return (0);

and read that when we execute the program with the following arguments:

hello this is a test

The variable string_so_far points to the string “hello” which was assigned as a result of the previous loop iteration. But I don't understand how? A step by step explanation would be really helpful.

Secondly, I came across this example in course material:

int countPrimes(int n)
   PrimeSet *p = new PrimeSet(n);
      return( p->countPrimeNumbers() );

It was stated that there's a memory leak here but I don"t really understand how, probably because I am not sure what exactly is happening here.


2 Answers 2


In the first example, you use malloc inside a loop for a variable. The malloc call reserves a block of memory and returns the block's first address. You need to delete to block with free if you no longer need it. If the programmer wishes to extend the memory block, the better alternative would be realloc. Read more about realloc at http://www.cplusplus.com/reference/cstdlib/realloc/.

In your second example, the object in which the pointer p points to is initialized on the heap and will remain to stay in the heap until the programmer uses delete. A safer alternative for creating objects on the heap is creating it on the stack, which will remove every data after a method's call is finished.

int countPrimes(int n){
   PrimeSet p(n);
   return( p.countPrimeNumbers() );

If memory management is not done properly like in the second example, the object can not be deleted after the only reference to it is lost, hence a memory leak happens.


In your second example, you allocate space for a PrimeSet object and initialise it, then you call the countPrimeNumbers function. The PrimeSet object still exists, it still occupies memory, it probably allocated more memory, and all that memory is still occupied but not accessible. That’s a memory leak: Memory that is occupied but unusable.


Not the answer you're looking for? Browse other questions tagged or ask your own question.