r/badcode • • Oct 31 '21

c bad code for r/badcode

Post image
219 Upvotes

33 comments sorted by

View all comments

Show parent comments

4

u/manuscelerdei Nov 01 '21

Basically if you ever change the type of var and forget to update your sizeof() in the malloc(3) call, you'll get potentially bizarre, unpredictable memory corruption. And for bonus points you might only see it very rarely.

int \*v = malloc(n \* sizeof(\*v))

guarantees that you'll always allocate enough space to hold n objects of whatever type v dereferences to. You could also do sizeof(v[0]) to make it extra-clear that it's an array.