uint8_t counter = 250;
for(int i = 0; i < 10; i++) {
counter++;
printf("%d ", counter);
}What will be the sequence of numbers printed? Why?
HINT
uint8_t has a maximum value of 255. What happens after that?int main() {
int8_t x = INT8_MAX;
printf("Before: %d\n", x);
x = x + 1;
printf("After: %d\n", x);
return 0;
}- What is the value of INT8_MAX?
- What will be printed as the "After" value?
- Why does this behavior occur?
uint8_t value = 0;
printf("Before: %u\n", value);
value--;
printf("After: %u\n", value);What will be printed as the "After" value and why?
HINT
Think about what happens when you subtract 1 from the minimum possible value of a variable.uint64_t calculate_buffer_size(uint64_t num_elements, uint64_t element_size) {
return num_elements * element_size;
}
int main() {
uint64_t elements = UINT64_MAX;
printf("Elements %zu\n", elements);
uint64_t elem_size = 2;
uint64_t buf_size = calculate_buffer_size(elements, elem_size);
void* buf = malloc(buf_size);
// ...
}- What would the size of the buffer allocated be?
HINT
Same as previous exercise think about what happens when you multiply the maximum size possible for a variable.void process_data(unsigned int length) {
unsigned int buf_size = length + 20; // Add 20 bytes for header
char* buffer = (char*)malloc(buf_size);
// ... use buffer ...
}- At what size of length would there be a problem?
- How would you modify this code to make it secure?
Complete the following function to safely add two integers without overflow, bool should indicate success or failure of the operation.
bool safe_add(int a, int b, int* result) {
// Your code here
}HINT
Use the max variables for each type.What's wrong with this loop and how would you fix it?
uint16_t i;
for(i = 1; i <= 65535; i++) {
// Process something
}