Answers/Solutions to Exercises in Chapter 4, Exercise 6

E6: Will the following program crash? Always, or sometimes, or never?
    #include <stdlib.h>

    int main()
    {
        char *p, *q;

        p = malloc(20);
        strcpy(p,"hello");

        q = p;
        printf("%s\n",q);

        p = realloc(p,1000);
        printf("%s\n",q);
        return 0;
    }

A6: It will compile fine. But it may sometimes crash. Why? A segment of 20 bytes is allocated, and p is made to point to it. Then the string "hello" is copied into the location pointed to by p. Then q is made pointing to the same location as p (i.e. to the beginning of the string "hello"). Then the segment p points to is either extended (if possible, and then everything is OK and q points to the beginning of the extended segment) or reallocated --- and then we might have a problem, for now q is a dangling reference as it points to the segment before it was reallocated.

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 4 Index