c - 为从函数中重新转换的变量释放动态分配的内存

时间:2018-02-19 13:38:03

标签: c memory heap free

我已经编写了一个函数,下面会格式化一个字符串。它删除了空格和字符 - ' - '。然后它会在每3个字符后插入一个空格。我malloc()函数中的两个字符串,但在退出函数之前我只有free()其中一个字符串。我认为这是内存泄漏的一个例子。有没有办法更好地设计这个功能,以免像这样泄漏内存?

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

char* FormatString(char* s) {

    /*Get string length*/
    int original_str_length = strlen(s);
    int num_elements_to_delete = 0;
    int i=0;
    int j=0;

    /*count chars '-' and ' ' to delete*/
    for (int i=0; i <= original_str_length; i++) {

        if((s[i] == '-') || (s[i] == ' ')) {
            num_elements_to_delete++;
        }
    }

    /*allocate new string to hold string minus '-' and ' '*/
    char* string_minus_chars = (char *) malloc(original_str_length - num_elements_to_delete);

    for (i=0; i <= original_str_length; i++) {

        /*if char is not '-' or ' ' copy to new string*/
        if((s[i] != '-') && (s[i] != ' ')) {

            string_minus_chars[j] = s[i];
            j++;
        }
    }

    /*Print the string*/
    printf("String minus chars is %s\r\n", string_minus_chars);
    int string_minus_chars_length = strlen(string_minus_chars);

    printf("string_minus_chars_length %d\r\n", string_minus_chars_length);

    int extra_spaces = (string_minus_chars_length) / 3;

    printf("Number of spaces needed is %d\r\n", extra_spaces);

    /*allocate new string with spaces*/
    char* string_with_spaces = (char *) malloc(sizeof(char)*(extra_spaces + string_minus_chars_length));

    int space_counter = 0;
    int index = 0;

    for (i=0; i <= strlen(string_with_spaces); i++) {

         if(space_counter == 3) {
             printf("str2 index is %d, str1 index is %d,space counter is %d, inserting space\r\n",i, index, space_counter);
             string_with_spaces[i] = ' ';
             space_counter = 0;

         }
         else {
             printf("str2 index is %d,str1 index is %d,space counter is %d,  copying %c\r\n", i, index,space_counter, string_minus_chars[index]);
             string_with_spaces[i] = string_minus_chars[index];
         space_counter++;
         index++;
         }

      }

    printf("String_with_spaces is:%s\r\n", string_with_spaces);

    free(string_minus_chars);
    return string_with_spaces;

}


int main(void) {

    char s[12] = "ABC-3-26--54";
    char* string_returned;

    string_returned = FormatString(s);

    printf("String returned is %s",string_returned);
}

1 个答案:

答案 0 :(得分:0)

每个分配的对象都有一个负责释放它的所有者。从函数返回此类对象时,调用者将成为所有者。然后,调用者有责任将其释放或将所有权传递给其他一些功能(或数据)。

在您的情况下,mainFormatString中分配的字符串的新所有者,因此main应该在完成时将其释放。