Incorrect use of sizeof() on malloced pointer type
Description
The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated.
Examples
Insecure Code
c
int *ptr = malloc(10); size_t size = sizeof(ptr);Secure Code
c
int *ptr = malloc(10); size_t size = 10;Remediation
Use a different method to determine the allocated memory size, such as maintaining a separate variable to track the allocated size.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0186 |
| Category | Generic |
| Severity | MEDIUM |
| CWE | CWE-467 |
| Confidence | MEDIUM |
| Impact | MEDIUM |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | sizeof, malloc |
| OWASP | N/A |
References
- https://github.com/struct/mms
- https://cwe.mitre.org/data/definitions/467
- https://dustri.org/b/playing-with-weggli.html
- https://g.co/kgs/PCHQjJ