Hello, I am sending a task to the server, they write: "Memory leaks". For input: 3

#include <stdio.h> #include <stdlib.h> #include <string.h> char *fibstr(int n) { int i=0; char *s1; char *s2; int len1=1; int len2=1; int sum=0; char *s=(char*)calloc(2,sizeof(char)); char *s3; if(n==1) { strcpy(s,"a"); return s; } if(n==2) { strcpy(s,"b"); return s; } for(i=2; i<=n; i++) { sum=len1+len2; len1=len2; len2=sum; } s1 = (char*)calloc(sum,sizeof(char)); s2 = (char*)calloc(sum,sizeof(char)); s3 = (char*)calloc(sum,sizeof(char)); strcpy(s1,"a"); strcpy(s2,"b"); for(i=2; i<n; i++) { strcpy(s3,strcat(s1,s2)); strcpy(s1,s2); strcpy(s2,s3); } free(s1),free(s2); return s3; } int main() { int n=0; scanf("%d",&n); char *s=fibstr(n); printf("%s",s); free(s); return 0; } 

Help properly clean the memory.

  • 2
    How many times have you allocated memory and how much is released? - Vladimir Martyanov
  • one
    singled out s1, s2, s3, freed s1 and s2 - MeloDy.
  • allocated 4 times released 2 times - nick_n_a
  • explain how to free the memory of the variable that you return - MeloDy.
  • @MeloDy. Well, once allocated more than released - there will be a leak. - Vladimir Martyanov

2 answers 2

explain how to free the memory of the variable that you return

Just like any other, here you have it all right. Error in another:

 char *s=(char*)calloc(2,sizeof(char)); char *s3; if(n==1) { strcpy(s,"a"); return s; } if(n==2) { strcpy(s,"b"); return s; } /* при n не равном 1 или 2 (как в вашем случае!) попадаем сюда, и память, выделенная для s, не освобождается */ 
  • Damn, thank you very much. corrected by writing it in the main function without an array. - MeloDy.

At the very beginning of the function, you allocate memory, whose address is entered into the variable s

 char *s=(char*)calloc(2,sizeof(char)); 

However, if n greater than 2 , then this memory in the function is not released.

In addition, you do not allocate enough memory for strings. Consider an example when n is 3 . In this case, the sum will also be 3 . However, in s3 you end up with the string "bab" , which contains 4 characters, including the terminating '\0' , and the memory has been allocated only for 3 characters. As a result, the program has an undefined behavior ..

  • freed s, and added this: - MeloDy.
  • s1 = (char *) malloc ((sum + 1) * sizeof (char)); s2 = (char *) malloc ((sum + 1) * sizeof (char)); s3 = (char *) malloc ((sum + 1) * sizeof (char)); - MeloDy.
  • @MeloDy. Yes, you need to take into account the final 0 lines. At the very beginning, you have len1 and len2 equal to 1. However, you correctly allocate memory equal to 2. However, when n is greater than 2, you forget about the final 0. :) - Vlad from Moscow
  • thanks, figured it out :) - MeloDy.