Open amayaling opened 4 months ago
offset = sprint_printint(buffer, va_arg(ap, int), 10, 1);
buffer += offset;
if (c == 'x') {
*buffer++ = '0';
*buffer++ = 'x';
offset = sprint_printint(buffer, va_arg(ap, int), 16, 0);
buffer += offset;
}
Length checking is only done in outside for loop, but values are directly added to buffer in sprint_printint/sprintptr, which can cause size of buffer to be exceeded (not memory safe)
Similar comments to sprintf
#define BUF_SZ 16
int
main(void)
{
char buf[BUF_SZ];
char str[BUF_SZ] = "STRING";
int a = 15, b = 25, sum;
sum = a + b;
// sprintf %s
sprintf(buf, "s: %s\n", str);
printf("%s\n", buf);
memset(buf, 0, BUF_SZ);
// sprintf %d
sprintf(buf, "%d + %d = %d\n", a, b, sum);
printf("%s\n", buf);
memset(buf, 0, BUF_SZ);
// snprintf %d (with buffer overflow)
snprintf(buf, "The sum of %d and %d is the value: %d\n", a, b, sum);
printf("%s\n", buf);
memset(buf, 0, BUF_SZ);
return 0;
}
Requires a few small fixes and the code should be good to go :D
The suggested fixes above are good and should be implemented. Additionally, there is some code redundancy here: for example, the two printints are almost the same and could be condensed into a single function (with a second helper function).
Emmanuel and I (Jaz) will do a code review on this :D