added free(M) to prevent memory leaks