Skip to content
Advertisement

Reuse char * pointer needs to free and malloc again?

I would like to implement a main function such as in order to execute system commands. The following code is currently used :

JavaScript

Because I need to enter other commands, I am currently using the same cmd_buffer by using free() before reallocating memory. Is it the right way to do ? Some other commands might be required in the future.

Advertisement

Answer

Your program can be be greatly simplified if you use a common function to execute the system call. It doesn’t even need to use malloc at all. Here’s a partial implementation [Please pardon the gratuitous style cleanup]:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement