i have a problem with free();
i have this simple program
Code:
#include <stdio.h>
#include <string.h>
char *foo(char *a, int n){
char *d,*c;
int i;
d = (char *)malloc(n*sizeof(char));
c=d;
n=strlen(a)-n;
for (i=n;i<strlen(a);i++){
*(d+i-n) = *(a+i);
}
*(d+i-n) = '\0';
return c;
}
int main(void){
char b[]="test";
printf("%s\n",foo(b,2));
getchar();
return 0;
}
if i put free(d) before return c; it will erase the contents of the array and so no string will be returned, i cant use free(d) in main since we have no d in main, what should i do? how can i free the allocated memory without losing the data that is stored?