...
This compliant solution ensures that the pointer returned by png_malloc()
is not null. It also uses the unsigned type size_t
to pass the length
parameter, ensuring that negative values are not passed to func()
.
This solution also ensures that the user_data
pointer is not null. Passing a null pointer to memcpy() would produce undefined behavior, even if the number of bytes to copy were 0. The user_data
pointer could be invalid in other ways, such as if i t pointed to freed memory. However there is no portable way to check that the pointer is valid, besides checking for null.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <png.h> /* From libpng */
#include <string.h>
void func(png_structp png_ptr, size_t length, const void *user_data) {
png_charp chunkdata;
if (length == SIZE_MAX) {
/* Handle error */
}
chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
if (NULL == chunkdata) {
/* Handle error */
}
if (NULL == user_data) {
/* Handle error */
}
/* ... */
memcpy(chunkdata, user_data, length);
/* ... */
} |
...