Considering the following line:
char *p = malloc( sizeof(char) * ( len + 1 ) );
Why is sizeof(char) used? It’s not necessary, is it? Or Is it just a matter of style?
What advantages does it have?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it’s a matter of style, because you’d expect
sizeof(char)to always be one.On the other hand, it’s very much an idiom to use
sizeof(foo)when doing amalloc, and most importantly it makes the code self documenting.Also better for maintenance, perhaps. If you were switching from
chartowchar, you’d switch towithout much thought. Whereas converting the statement
char *p = malloc( len + 1 );would require more thought. It’s all about reducing mental overhead.And as @Nyan suggests in a comment, you could also do
for zero-terminated strings and
for ordinary buffers.