I wanted to know what happens when I write a word less than 100 characters:
char cad[100];
printf("Cadena: ");
scanf("%s", cad);
since using strlen()
I was able to verify that the size of the array is changed.
Now the question is: What happens to that memory that is no longer going to be used, for example when going from an array of size 100 to an array of size 5? Is that memory released? Is this done by the operating system or what?
In the example you have given nothing bad happens. You have declared an array with room to store up to 100 characters. If your intention is to store a text string in said array, you can store up to 99 characters (remember that in C strings must be with
\0
, which occupies a position).As long as you don't exceed the length of 99 characters, your program will work, at least at that point, correctly.
You are getting confused on this.
strlen
is a function that indicates the length of the stored string ... not the length of the array. That array you declared is fixed-size and, as expected, its size cannot be changed in any way at runtime.You can check how the size of the array does not change using
sizeof
(the example will not work with dynamic arrays):It happens that it is not used... it is wasted. Normally nothing happens since the system usually has resources to spare... but you have to be careful because if you overdo it then the program will fail sooner or later when the system runs out of resources.
If you need a finer adjustment, which allows you to adapt to the needs of each moment, you have to change to dynamic size arrays. Dynamic memory is much more flexible but also requires you to control its life cycle.
You have already seen that it is not. The array you have declared is stored on the program's stack and that memory will be freed automatically when the variable goes out of scope.
On the other hand, if the array were dynamic, it is necessary to call to
free
free the memory and not create memory leaks.Heap memory is controlled directly by the application. In the case of fixed size arrays don't worry about memory management as there is little you can do about it.