Allocating memory to char* C language

后端 未结 7 1634
执笔经年
执笔经年 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:31

    As has been pointed out, you missed allocating space for the terminating NUL chararacter. But I also wanted to point out a couple of other things that can make your code more concise.

    By definition, sizeof(char) is always 1, so you can shorten your allocation line to:

    tempSides = (char*)malloc(strlen(inSides) + 1);
    

    Another thing is that this looks like you are doing to duplicate the string. There is a built in function that does that for you:

    tempSides = strdup(inSides);
    

    This handles getting the length, allocating the correct number of bytes and copying the data.

提交回复
热议问题