Question: C programming The program needs to protect against integer overflow. * * 1. Detect when an overflow occurred. * 2. If an overflow occurs, discard
C programming
The program needs to protect against integer overflow.
* * 1. Detect when an overflow occurred.
* 2. If an overflow occurs, discard the current string * and copy (not append) the new string to buffer.
#include
#include
#include
#include
#include
#define MAX_SIZE UCHAR_MAX
typedef unsigned char str_size_t;
str_size_t size;
char *buffer;
/*
* The purpose of this program is to allow a user to continually
* append text to a string, until CTRL-C is entered.
*
* Example Output:
*
* Hit CTRL-C to Exit.
*
* Input -> abc
* Output -> 3 {abc}
* Input -> def
* Output -> 6 {abcdef}
* Input -> ^C
* Output -> 6 {abcdef}
*
* The program needs to protect agains integer overflow.
*
* 1. Detect when an overflow occurred.
* 2. If an overflow occurs, discard the current string
* and copy (not append) the new string to buffer.
*/
void print_output()
{
printf ("Output -> %u {%s} ", size, buffer);
}
void signal_handler (int sig)
{
printf(" ");
print_output();
exit(0);
}
int main (int argc, char** argv)
{
int result;
char *tmp;
signal(SIGINT, signal_handler);
size = 0;
buffer = malloc(MAX_SIZE);
tmp = malloc(MAX_SIZE);
memset(buffer, 0, MAX_SIZE);
printf ("Hit CTRL-C to Exit. ");
while (1)
{
printf ("Input -> ");
result = scanf(" %[^ ]", tmp);
size = (size + strlen(tmp));
/* TODO - Solution */
buffer = realloc(buffer, size);
strcat(buffer, tmp);
print_output();
}
/* Any code here is unreachable. */
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
