Is it necessary to multiply by sizeof( char ) when manipulating memory?
c, malloc, memory-management, sizeof
Solution
While its not necessary, I consider it good practice to leave in the sizeof( char ) because it makes the code more readable and avoids the use of a magic number. Also, if the code needs to be changed later so that instead of a char it's mallocing the size of something into a pointer for that object, it's easier to change the code than if you have just a "1".
Problem
When using malloc and doing similar memory manipulation can I rely on sizeof( char ) being always 1? For example I need to allocate memory for N elements of type `char`. Is multiplying by `sizeof( char )` necessary: ``` char* buffer = malloc( N * sizeof( char ) ); ``` or can I rely on sizeof( char ) always being 1 and just skip the multiplication ``` char* buffer = malloc( N ); ``` I understand completely that `sizeof` is evaluated during compilation and then the compiler might even compile out the multiplication and so the performance penalty will be minimal and most likely zero. I'm asking mainly about code clarity and portability. Is this multiplication ever necessary for `char` type?