I've been trying to be more "memory-aware" in my C programming when I found out about the malloc
method and similar memory management methods. However, when I tried to use realloc
to allocate as little memory as possible to a char*
instance in my program, I found that it wasn't holding as much data as I thought it would.
Here is my code:
int foo(char * arg){
if(condition){
//code here
}else if(other_condition){
char * cmd = malloc(5);
fgets(cmd,sizeof(cmd),stdin);
//more code here
if(another_condition){
//more code
cmd = realloc(cmd,new_size) //once in this if block, but also once in another block
fgets(cmd,sizeof(cmd),stdin);
//more code
}
//more else-if blocks here
free(cmd)
}
//more else-if blocks here
}
To be specific, in the above code snippet, new_size
was 255, although it has been set to other sizes in other places. The problem is that when I run the program I only get 7 letters of my input.
Example output:
...
Enter filename: document1
Loading file "documen"
Load failed
...
(here the next time fgets is called it fails because "t1" is not valid input for the program)
I understand that it's receiving "t1"
because I'm not clearing the input buffer, but what I want to solve is the fact that I'm only receiving the first 7 characters of the input. If I call sizeof(cmd)
in the middle, it tells me that the memory occupied by cmd
is 8. I also tried allocating the memory using char * cmd = malloc(5 * sizeof(char))
and cmd = realloc(cmd,255 * sizeof(char))
but it didn't solve the problem. I should probably mention that if I declare the variable using the char cmd[255]
syntax and I don't call malloc
, realloc
, or free
anywhere this problem no longer comes up.