I have a problem with dynamic memory management. Let's say I have a trivial command shell, call it tsh, that takes a command from the user and then echoes it back, and continues doing that until the user hits ^C.
Here's the problem. I need to create a character array and have it be of a variable length, since I don't know the length of the input. I need to allocate the memory for it dynamically, and not allow for memory overflow.
Here are three trivial programs I've written. I haven't tested any of them, but I know they wouldn't work.
Program 1:
#include <stdio.h> int main( int argc, char **argv ){ char *cmd; for(;;){ cmd = fgets( stdin ); printf( "%s\n", cmd ); } return 0; }
This code creates a string variable cmd and gets its value from the user through fgets( stdin ). This obviously won't work, because cmd is not dynamically allocated, so its length can not be changed.
Program 2:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main( int argc, char **argv ){ char *cmd = (char *) malloc( 8 ); for(;;){ cmd = realloc( cmd, strlen( (cmd = fgets( stdin )) ) ); printf( "%s\n", cmd ); } return 0; }
This program dynamically allocates memory for the string. Every time the user inputs a string, the amount of memory allocated changes to the length of the input. So I have to do three things:
1. Set cmd to fgets( stdin )
2. Find the length of fgets( stdin )
3. Reallocate memory.
Here I did it in the order 1, 2, 3. The problem with this is that cmd is set to fgets( stdin ) before its memory is reallocated, so it won't be the right size. Thus Step 3 has to come before Step 1. Step 3 can't be completed unless I know the length of the string, so the order has to be 2, 3, 1. I can't do Step 2 until I have an input to get the length of. Thus, Step 1 must come before Step 2. It's a chicken and egg problem.
Program 3:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main( int argc, char **argv ){ char *cmd = (char *) malloc( 8 ); for(;;){ cmd = realloc( cmd, 1024 ); cmd = fgets( stdin ); cmd = realloc( cmd, strlen(cmd) ); printf( "%s\n", cmd ); } return 0; }
This program first sets the amount of memory allocated to a really high value, gets the input, and then reallocates it to reduce the amount of memory to the length of the input. The problem with this is a. too much overhead from the size of the initial block of memory, and b. the contents of the larger block are not necessarily copied to the smaller block, so loss of data is likely.
So yeah, there seems to be no logical way to create a variable-length string and set its length according to input. Is there any way to do this?
Please help me. This is very important!