Allocating memory to char* C language

后端 未结 7 1631
执笔经年
执笔经年 2021-01-05 06:47

Is it the correct way of allocating memory to a char*.

char* sides =\"5\";

char* tempSides;

tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
         


        
7条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 07:35

    No, not really. As others have already noted, you need to allocate space for the NUL terminator.

    In addition, you generally should not cast the return from malloc. It can cover up a bug where you've forgotten to #include the correct header. Multiplying by sizeof(char) is also pointless, since the standards (both C and C++) define sizeof(char) to always be 1.

    Finally, every call to malloc should include a test of the result. I'd wrap the whole thing up into a function:

    char *dupe_string(char const *string) { 
        char *temp;
        if (NULL!=(temp=malloc(strlen(string)+1)))
            strcpy(temp, string);
        return temp;
    }
    

提交回复
热议问题