📢 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 attempts to copy a substring.

      #include #include #include char* copy_substring(const char* source, int start_index, int length) {     char* dest = (char*)malloc(length + 1);     if (dest == NULL) return NULL;     strncpy(dest, source + start_index, length);     dest[length] = '\0'; // Null-terminate     return dest; } int main() {     const char* original = "Programming"; // Length 11     char* sub = copy_substring(original, 5, 10); // start_index=5, length=10     if (sub) {         printf("Substring: %s ", sub);         free(sub);     }     return 0; } What is the most likely issue with copy_substring when called as in main?
      A It will correctly copy "amming". Correct Answer Incorrect Answer
      B It will copy "amming" but might read beyond the bounds of original, leading to undefined behavior. Correct Answer Incorrect Answer
      C It will copy "amming" and then crash due to dest[length] = '\0' accessing invalid memory. Correct Answer Incorrect Answer
      D It will cause a memory leak. Correct Answer Incorrect Answer
      E It will return NULL because malloc fails. Correct Answer Incorrect Answer

      Solution

      Correct Answer: B (source + start_index points to "amming". length is 10. strncpy will attempt to copy 10 characters starting from 'm'. However, "amming" only has 6 characters. strncpy will read 4 characters from "amming" and then 6 more characters from memory *after* "Programming", potentially causing a read out of bounds.)

      Practice Next
      ask-question