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?
, .
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, . , :
char**
if (*out_value_ptr == NULL) *out_value_ptr =(char*) malloc(length + 1);
, . , , . - , . .
, , , . , , . , , , .
, //, , , . , ( ) , , . .
, - ( ++, char ** C. , .
, out_value . , .
recv, :
ssize_t recv(int socket, void *buffer, size_t length, int flags);
:
out_value. char*. , "" . char**
out_value
char*
, . , , . , , , . , , .
-, , , ANSI C. ++. "< C, -, cout.
, () , . char *, malloc() ( malloc() C), , . , char char **, ++ ( C, ").
char *
malloc()
char **
, , / , . , , , malloc(), free(). , , , . , validate_input , malloc() . , , , , . .
free()
, ,
malloc
Source: https://habr.com/ru/post/1749036/More articles:Setting the service url at runtime - c #TinyMCE or HTML5 contentEditable attribute? - html5create jQuery plugins to automatically create page load numbering - jquery-pluginsis_dir does not recognize folders - phpSilverlight combobox performance issue - performanceProblems using Maven to initialize a local thinkite project (App Engine sample) in Eclipse - javacore-plot and NSDate (iPhone) - dateHow to disable Mac screensaver? - objective-cHow to save esri map as image file - pixelВыпадающее окно OnSelectedIndexChanged не работает - c#All Articles