Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory to char* C language

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

char* sides ="5";

char* tempSides;

tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
like image 748
boom Avatar asked Jun 04 '10 05:06

boom


1 Answers

Almost. Strings are NUL terminated, so you probably want to allocate an extra byte to store the NUL byte. That is, even though sides is 1 character long, it really is 2 bytes: {5,'\0'}.

So it would be:

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

and if you wanna copy it in:

strcpy(tempSides, sides);
like image 132
Claudiu Avatar answered Oct 10 '22 11:10

Claudiu