str = (char*) malloc(sizeof(char*)); allocates a block of four bytes (typically).
The while loop will a probably go around more than four times, causing you to overrun your four byte buffer, which corrupts the heap, which puts the program in an indetermate state.