I am trying to return a pointer from a function and use the return in a different function . But I am getting memory leak. Please help. The test code which I wrote and detected with memory leak by CPPCheck.

#

# include < stdio.h >
# include < malloc.h >

# include < string.h >

char* replace ( char* st, char* word, char *replaceWith );

int main ( void ) 

{

    char str[] = "Hello how are ## and what are ## doing ?";

    char word[]="##";

    char replaceWith[]="you";

    printf("%s",replace(str,word,replaceWith));

    getchar();

    return 0;
}

char* replace(char* st,char* word,char *replaceWith)
{

 int i = 0;

 char *sr,*s,*ret;

 int oldlen;

 int count = 0;

 int newlen;

 int stlen;

 s=(char *)malloc(strlen(st) + 1);

 strcpy(s, st);

 oldlen=strlen(word);

 newlen=strlen(replaceWith);

 for (i = 0; s[i]! = '\0'; )

 {

     if( memcmp( &s[i], word, oldlen ) == 0)
     {

        count++;

        i+=oldlen;

     }

     else
     {
         i++;
     }

 }
 sr= (char *) malloc (i+1+count*(newlen-oldlen));

 ret = (char *) malloc (i+1+count*(newlen-oldlen));

 ret=sr;

 while(*s)
 {
     if(memcmp( s, word, oldlen) == 0)
     {
         memcpy(sr, replaceWith, newlen);

         s+ = oldlen;

         sr+ = newlen;

     }
     else
     {

         *sr++ = *s++;

     }
 }

 *sr = '\0';

 return ret;

}

Thanks for your help

Thanks !!! I got the answer :)
Please find the below code.

#include<stdio.h>
#include<malloc.h>
#include<string.h>

char* replace ( char* st, char* word, char *replaceWith );

int main ( void ) 
{
    char str[] = "Hello how are ## and what are ## doing ?";

    char word[]="##";

    char replaceWith[]="you";

    char * ret = replace(str,word,replaceWith);
    printf("%s",ret);
    free(ret); //freeing the allocated memory 
    getchar();

    return 0;
}

char* replace(char* st,char* word,char *replaceWith)
{

 int i = 0;

 char *sr,*s,*ret, *temps;

 int oldlen;

 int count = 0;

 int newlen;

 //int stlen;

 s=(char *)malloc(strlen(st) + 1);
 temps = s; // storing the address of s in a temp location
 strcpy(s, st);

 oldlen=strlen(word);

 newlen=strlen(replaceWith);

 for (i = 0; s[i]!= '\0';)

 {

     if( memcmp( &s[i], word, oldlen ) == 0)
     {

        count++;

        i+=oldlen;

     }

     else
     {
         i++;
     }

 }
 sr= (char *) malloc (i+1+count*(newlen-oldlen));

 ret=sr;

 while(*s)
 {
     if(memcmp( s, word, oldlen) == 0)
     {
         memcpy(sr, replaceWith, newlen);

         s += oldlen;

         sr += newlen;

     }
     else
     {

         *sr++ = *s++;

     }
 }

 *sr = '\0';
 free(temps); // freeing the memory allocated for s
 return ret;

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.