...
| Code Block | ||||
|---|---|---|---|---|
| ||||
int f(void) { /* assuming 32-bit pointer, 32-bit integer */ size_t i; int **matrix = (int **)calloc(100, 4); if (matrix == NULL) { return -1; /* handle errorIndicate calloc() failure */ } for (i = 0; i < 100; i++) { matrix[i] = (int *)calloc(i, 4); if (matrix[i] == NULL) { return -1; /* handle errorIndicate calloc() failure */ } } return 0; } |
Compliant Solution
This compliant solution replaces the hard-coded value 4 with sizeof(int *):
| Code Block | ||||
|---|---|---|---|---|
| ||||
int f(void) { size_t i; int **matrix = (int **)calloc(100, sizeof(*matrix)); if (matrix == NULL) { return -1; /* handle errorIndicate calloc() failure */ } for (i = 0; i < 100; i++) { matrix[i] = (int *)calloc(i, sizeof(**matrix)); if (matrix[i] == NULL) { return -1; /* handle errorIndicate calloc() failure */ } } return 0; } |
Also see MEM02-C. Immediately cast the result of a memory allocation function call into a pointer to the allocated type for a discussion on the use of the sizeof operator with memory allocation functions.
...