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


    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 "mming". Correct Answer Incorrect Answer
    B It will copy "mming" but might read beyond the bounds of original, leading to undefined behavior. Correct Answer Incorrect Answer
    C It will copy "mming" 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 "mming". length is 10. strncpy will attempt to copy 10 characters starting from 'm'. However, "mming" only has 5 characters. strncpy will read 5 characters from "mming" and then 5 more characters from memory *after* "Programming", potentially causing a read out of bounds.)

    Practice Next
    ask-question