understanding memory leaks in C/C++

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 = '';         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 it 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.