Returns the string highlighted by malloc?

I create a function that returns a string. The size of the string is known at runtime, so I plan to use it malloc(), but I do not want to give the user responsibility for the call free()after using the return value of the function.

How can this be achieved? How do the other functions that return line ( char *s) (eg, getcwd(), _getcwd(), GetLastError(), SDL_GetError())?

+4
source share
6 answers

Your task is that something should free resources (i.e. call free()).

free() (., , strdup), , free. , , foo_destroy. , struct, , , (, ).

. , , , , , . apache2 apr_pool. , free() . . ( ) .

, C ( malloc() d), , . , , .

, , char *:

  • (, strdup, get_current_dir_name getcwd ) , .

  • (, strerror_r getcwd ) , .

  • : getcwd man:

POSIX.1-2001, Linux (libc4, libc5, glibc) getcwd() malloc(3), buf - NULL. size, size , buf . free(3) .

  • , , / (yuck - ). . strerror strerror_r.

  • ( ), .

  • (, libxml) free (xmlFree() )

  • (, apr_palloc) .

+5

C. , malloc() free() , malloc().

- (, ++) , , , C.

, -, , , . , , , :

char test1[]="this is a test";
char *test2="this is a test";  

:

readString(test1); // (or test2) 

char * readString(char *abc)
{
    int len = strlen(abc);
    return abc;
}

len= 14

, , :

char *test3; 

, , :

test3 = malloc(strlen("this is a test") +1);  

, , . len == 0 1- readString(). , readString() :

readString(char *abc, int sizeString);  Then size information as an argument can be used to create memory:    

void readString(char *abc, size_t sizeString)
{
    char *in;
    in = malloc(sizeString +1);

    //do something with it  
    //then free it
    free(in);

}  

:

int main()
{
     int len;
     char *test3;

     len =  strlen("this is a test") +1; //allow for '\0'  
     readString(test3, len);
     // more code
     return 0;
}
+1

. , . , .

, :

for (a lot of iterations)
{ 
    params = get_totally_different_params();
    char *str = your_function(params);
    do_something(str);
    // now we're done with this str forever
}

malloc , malloc , , , malloc .

- :

int output_size(/*params*/);
void func(/*params*/, char *destination);

destination output_size(params), - recv API:

int func(/*params*/, char *destination, int destination_size);

:

< desination_size: this is the number of bytes we actually used
== destination_size: there may be more bytes waiting to output

, , - .

+1

C.

, , , free

++. shared_ptr ..

0

.

, . .

void release_resources(struct opaque *ptr);

, .

0

atexit (http://www.tutorialspoint.com/c_standard_library/c_function_atexit.htm). , , .

#include <stdlib.h>
#include <string.h>
#include <malloc.h>
char* freeme = NULL;
void AStringRelease(void)
{
    if (freeme != NULL)
        free(freeme);
}
char* AStringGet(void)
{
    freeme = malloc(20);
    strcpy(result, "A String");
    atexit(AStringRelease);
    return freeme;
}
0

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


All Articles