I see code like ...

Q

I see code like
char *p = malloc(strlen(s) + 1);
strcpy(p, s);

Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?

✍: Guest

A

It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and in some circumstances may help by introducing a size_t into the expression;

2016-06-21, 404👍, 0💬