📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!

  • google app store apple app store
  • ✖

      Question

      A C function pop(Stack* s) is designed to remove and

      return the top element from a stack. #include #include #define MAX_SIZE 10 typedef struct {     int arr[MAX_SIZE];     int top; } Stack; int pop(Stack* s) {     // Assume stack is initialized with s->top = -1 for empty     return s->arr[s->top--]; // Potential bug here } If pop() is called on an empty stack (where s->top is -1), what is the most likely immediate consequence?
      A The function will return a garbage value without crashing. Correct Answer Incorrect Answer
      B The program will crash due to accessing invalid memory (segmentation fault). Correct Answer Incorrect Answer
      C The s->top will become -2, leading to an overflow. Correct Answer Incorrect Answer
      D The stack will correctly remain empty. Correct Answer Incorrect Answer
      E A compile-time error will occur. Correct Answer Incorrect Answer

      Solution

      • Dry Run: o Call pop() on an empty stack where s->top is -1. o The expression s->arr[s->top--] attempts to access s->arr[-1]. o s->arr is an array of ints. Accessing arr[-1] is an out-of-bounds memory access. o This is undefined behavior. On most modern operating systems, attempting to read from a memory address that is not part of the program's allocated memory space (or is protected) will trigger a segmentation fault, causing the program to crash. o After the access, s->top would be decremented to -2, but the crash would likely occur before this side effect is fully processed or becomes relevant. • Why Correct Answer (B): The program will crash due to accessing invalid memory (segmentation fault). o This is the most common and immediate consequence of accessing an array with a negative index in C.

      Practice Next
      ask-question