Dynamically allocating memory for a const char string using malloc ()

I am writing a program that reads a value from an .ini file and then passes the value to a function that accepts PCSTR (i.e. const char *). Function getaddrinfo().

So, I want to write PCSTR ReadFromIni(). To return a constant string, I plan to allocate memory with malloc()and translate the memory into a constant string. I can get the exact number of characters that were read from the .ini file.

Is this technology good? I really don't know what else to do.

The following example works fine in Visual Studio 2013 and prints "hello" as desired.

const char * m()
{
    char * c = (char *)malloc(6 * sizeof(char));
    c = "hello";
    return (const char *)c;
}    

int main(int argc, char * argv[])
{
    const char * d = m();
    std::cout << d; // use PCSTR
}
+4
3

"" :

char* c = (char*)malloc(6*sizeof(char));
// 'c' is set to point to a piece of allocated memory (typically located in the heap)
c = "hello";
// 'c' is set to point to a constant string (typically located in the code-section or in the data-section)

c , , . :

int i = 5;
i = 6;

, "" , .

:

char* m()
{
    const char* s = "hello";
    char* c = (char*)malloc(strlen(s)+1);
    strcpy(c,s);
    return c;
}

, , char* p = m(), free(p) - ...

+7

- .

const char * m()
{
    static char * c = NULL;
    free(c);

    c = malloc(6 * sizeof(char));
    strcpy(c, "hello"); /* or fill in c by any other way */
    return c;
}    

, , m(), c . , .

+2

. .

c = "hello";  

, malloc .

const char * m()
{
    char * c = (char *)malloc(6 * sizeof(char));
    fgets(c, 6, stdin);
    return (const char *)c;
}    
+1

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


All Articles