Are you running on CPU or GPU?
The main problem with this function is that it does not know in advance how many non-zero elements there are and so it is tricky to allocate the output properly in advance.