You are on page 1of 2

Lab Assignment - 3

1. Why is it unsafe using gets() in C/C++? Write a C/C++ program to demonstrate the same.
Further, rewrite the program using gets() alternative.
2. Analyze the following code fragment for a string whose length is more than 10 bytes and find the
error in code. What could be the possible reasons for the error and how do we rectify it?
#include <stdio.h>
#include <string.h>

int main(void)
{
int len = 0;
char str[10] = {0};

printf("\n Enter the name \n");

gets(str);

printf("\n len = [%d] \n",

len);

len = strlen(str);
printf("\n len of string entered is : [%d]\n", len);

return 0;
}
3. A buffer, in terms of a program in execution, can be thought of as a region of computer’s main
memory that has certain boundaries in context with the program variable that references this
memory. A buffer is said to be overflown when the data (meant to be written into memory
buffer) gets written past the left or the right boundary of the buffer. This way the data gets
written to a portion of memory which does not belong to the program variable that references
the buffer. Due to this, a program could crash or give unexpected results. Buffer o v e r f l ow
also leads to buffer overflow attacks. Write a C program to demonstrate buffer overflow. Also,
discuss the prevention strategies to avoid buffer overflow attacks.
4. What will be the output of the following code?
void function() {
int i,j,k;
unsigned int u,v;
i = INT_MAX; // 2147483647
i++;
printf("i = %d, ", i);
j = INT_MIN; // -2147483648
j--;
printf("j = %d, ", j);
k = INT_MIN; // -2147483648
k = abs(k);
printf("k = %d, ", k);
u = UINT_MAX; // 4294967295
u++;
printf("u = %u, ", u);
v = 0; v--;
printf("v = %u", v); }
5. Identify the computer vulnerability that exist in the below mentioned codes. Rectify the code
to avoid the identified vulnerability.
a)
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
char * buffer = (char *) malloc(256);
bool error = true;

if (error)
free(buffer);

// [...]

if (error)
printf("%lu\n", strlen(buffer)); //<- Use after free
}
b)
#include <stdbool.h>
#include <stdlib.h>

int main() {
char * buffer = (char *) malloc(256);
bool error = true;

if (error)
free(buffer);

// [...]

free(buffer); // second free


}

You might also like