Is it the correct way of allocating memory to a char*.
char* sides =\"5\";
char* tempSides;
tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
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;
}