Dynamically allocating memory for const char string using malloc()

半世苍凉 提交于 2019-12-05 15:21:20

The second line is "horribly" wrong:

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)

You are assigning variable c twice, so obviously, the first assignment has no meaning. It's like writing:

int i = 5;
i = 6;

On top of that, you "lose" the address of the allocated memory, so you will not be able to release it later.

You can change this function as follows:

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

Keep in mind that whoever calls char* p = m(), will also have to call free(p) at some later point...

One way is to return a local static pointer.

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;
}    

This way, whenever the next time m() is called, c still points to the memory block allocated earlier. You could reallocate the memory on demand, fill in new content, and return the address.

NO. This is not OK. When you do

c = "hello";  

the memory allocated by malloc lost.
You can do as

const char * m()
{
    char * c = (char *)malloc(6 * sizeof(char));
    fgets(c, 6, stdin);
    return (const char *)c;
}    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!