...
Code Block | ||
---|---|---|
| ||
#include <stdlib.h>
#include <stdio.h>
enum { MAXLINE = 1000 };
size_t calc() {
char line[MAXLINE], c;
size_t size = 0;
while ( (c = getchar()) != EOF && c != '\n') {
line[size] = c;
size++;
if (size >= MAXLINE)
break;
}
return size;
}
int main(void) {
char *line = malloc(calc());
if (line == NULL) {
/* Handle malloc() error */
}
/* ... */
free(line);
}
|
Wiki Markup |
---|
However, if no characters are entered, {{calc()}} will return {{0}}. Because there is no validation on the result of {{calc()}}, a {{malloc(0)}} \[[MEM04-A. Do not make assumptions about the result of allocating 0 bytes]\] could occur, which could lead to a buffer overflow. |
...
Code Block | ||
---|---|---|
| ||
#include <stdlib.h>
#include <stdio.h>
enum { MAXLINE = 1000 };
size_t calc() {
char line[MAXLINE], c;
size_t size = 0;
while ( (c = getchar()) != EOF && c != '\n') {
line[size] = c;
size++;
if (size >= MAXLINE)
break;
}
return size;
}
int main(void) {
size_t size = calc();
if (!size) {
/* Handle invalid size */
}
char *line = malloc(size)
if (line == NULL) {
/* Handle malloc() error */
}
/* ... */
free(line);
}
|
Risk Assessment
...