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

#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

int main(int argc, char *argv[]) {
    char *string, *string_so_far;
    int i, length;     length = 0;
    for(i=0; i&lt;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 &lt; 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-&gt;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.
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.