C, when to allocate and free memory - before a function call, after a function call ... etc.

I work with my first direct C project, and it's been a while since I worked on C ++. Thus, managing the entire memory is a bit fuzzy.

I have a function that I created that will check some input. In the simple example below, it simply ignores spaces:

int validate_input(const char *input_line, char** out_value){

    int ret_val = 0; /*false*/
    int length = strlen(input_line);
    out_value =(char*) malloc(sizeof(char) * length + 1);

    if (0 != length){

        int number_found = 0;
        for (int x = 0; x < length; x++){

            if (input_line[x] != ' '){ /*ignore space*/

                /*get the character*/
                out_value[number_found] = input_line[x];
                number_found++; /*increment counter*/
            }
        }
        out_value[number_found + 1] = '\0';

        ret_val = 1;
    }

    return ret_val;

}

Instead of allocating memory inside the function for out_value , should I do this before I call the function, and always expect the caller to allocate memory before moving on to the function? As a rule, if any memory allocated inside a function is always freed before the function returns?

+3
8

, .

1/ , , , . , .

2/ . , , . , - .

char, , :

int validate_input (const char *input_line, char **out_value_ptr) {
    : :
    *out_value_ptr =(char*) malloc(length + 1); // sizeof(char) is always 1
    : :
    (*out_value_ptr)[number_found] = input_line[x];
    : :

, , . , .

, . , a char**, NULL, . , :

    if (*out_value_ptr == NULL)
        *out_value_ptr =(char*) malloc(length + 1);
+7

, . , , . - , . .

, , , . , , . , , , .

+2

, //, , , . , ( ) , , . .

, - ( ++, char ** C. , .

+2

, out_value . , .

recv, :

 ssize_t recv(int socket, void *buffer, size_t length, int flags);
+1

:

  • .
  • . (, / ).
  • . .

:

  • , , , .
  • , . . .
  • .
+1

out_value. char*. , "" . char**

, . , , . , , , . , , .

0

-, , , ANSI C. ++. "< C, -, cout.

, () , . char *, malloc() ( malloc() C), , . , char char **, ++ ( C, ").

, , / , . , , , malloc(), free(). , , , . , validate_input , malloc() . , , , , . .

, ,

0

:

  • , . , / . malloc() , .
  • , , , , .
  • In cases where your function needs to be allocated, consider letting the caller pass a callback to the distributor that he uses instead of a direct call malloc. This allows your function to allocate when it is needed and how much is needed, but it allows the caller to control how and where this memory is allocated.
0
source

Source: https://habr.com/ru/post/1749036/


All Articles