At the time you return str_buf it points to the last character: '\0'. To free this memory you would need to capture that pointer from remove_space so you can free it main. Edit: that would not work either actually since str_buf has been altered since you malloced it. You could pass a pointer to pointer (**p) to the function as a remedy and alter the original string from within your remove_space function.