递归方法中返回后的C-free()

递归方法中返回后的C-free(),c,recursion,malloc,free,C,Recursion,Malloc,Free,我必须编写一个递归返回末尾字符串的函数。我们可以使用以下3种功能: #include <stdio.h> #include <stdlib.h> int length(char* s) { int n = 0; while (*s != '\0') { n++; s++; } return n; } void copy(char* s, int n, char* t) { int i = 0;

我必须编写一个递归返回末尾字符串的函数。我们可以使用以下3种功能:

#include <stdio.h>
#include <stdlib.h>

int length(char* s) {
    int n = 0;
    while (*s != '\0') {
        n++;
        s++;
    }

    return n;
}


void copy(char* s, int n, char* t) {
    int i = 0;
    while (i < n) {
        t[i] = s[i];
        i++;
    }
}

char* putBack(char* s, char c) {
    const int n = length(s);
    char* r = malloc(sizeof(char) * (n + 2));
    copy(s, n, r);
    r[n] = c;
    r[n + 1] = '\0';
    return r;
}
例如,如果我有“call”作为输入,那么“llac”就是输出。因此,该方法应该有效。我现在的问题是如何在每次调用后使用
free()
清理
putBack()
(有一个malloc)的保留空间


谢谢你的帮助!:)

首先,当
*指针='\0'
时,您必须让
reverseRec
返回某些内容,以避免使用“返回值”时出现未定义的行为非void函数的一种,其执行在末尾,而不执行
return
语句。看起来预期的功能根本不需要动态分配。让操作系统进行清理将是最简单的方法@“米凯卡特,在这种情况下,我认为这不是一个好建议。”尤金尼什。OP可以选择在
*指针=='\0'
案例中不使用
malloc()
putBack()
。然后这将是避免传递未通过
malloc()
family分配的指针的安全方法。
char* reverseRec(char* s) {
    char* pointer = s;
    char* string;
    if (*pointer == '\0') { 
        return pointer--;
    }
    else{
        string = reverseRec(pointer + 1);
        string = putBack(string, *pointer);
        return string;
    }
}