...
Noncompliant Code Example (realloc())
Reallocating memory using the using realloc() function is a regenerative case of can have the same problem as freeing memory. The realloc() function deallocates de-allocates the old object and returns a pointer to a new object. Using Using realloc() to resize dynamic memory may inadvertently expose sensitive information, or it may allow heap inspection as described in Fortify Taxonomy: Software Security Errors [Fortify 2006] and NIST's Source Code Analysis Tool Functional Specification [Black 2007]. When realloc() is called, it may allocate a new, larger object, copy the contents of secret to this new object, free() the original object, and assign the newly allocated object to secret. However, the contents of the original object may remain in memory.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *secret;
/* initialize secret */
size_t secret_size = strlen(secret);
/* ... */
if (secret_size > SIZE_MAX/2) {
/* handle error condition */
}
else {
secret = (char *)realloc(secret, secret_size * 2);
}
|
...