Allocating memory to char* C language

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

    The correct way of allocation dynamic memory to tempSides is as shown below:

    char* sides ="5";
    char* tempSides;
    tempSides = (char*)malloc((strlen(sides) + 1) * sizeof(char));
    

    char* stores a string data, similar to char[]. Strings are null (\0) terminated. So extra one byte should be allocated for null character storage.

    Dynamically allocated memory block must be freed using free() after it's use is over. If not freed, memory leak would happen.

    free(tempSides);
    

    One the memory is freed, NULL must be assigned to prevent it from being a dangling pointer.

    tempSides = NULL;
    

提交回复
热议问题