I have this code:
char* texto=(char*)malloc(11);//Retorno un arrays de 10 char
strcpy(texto,"Hello World");
texto[4]='\0';//Recortamos la cadena.
for (int i=5;i<11;i++)
free(&texto[i]);//Liberamos el espacio que no nesecitamos.
This stops the executable for me. But if I did this:
texto[7]='\0';
for (int i=8;i<11;i++)
free(&texto[i]);
The executable ends perfectly. Because? And how do I solve it?
I got this page:
Uncle C(GCC) There I could see this error:
double free or corruption (top)
/srv/wrappers/c-gcc: line 5: 3868 Aborted (core dumped) ./.bin.tio "$@" < .input.tio
But why if I am freeing memory that I reserve to trim the string?
Any help or advice. The idea is just to trim the string and free up the space I don't need.
Memory management does not work as you think. When you ask for memory:
You ask for an entire block of memory, this block is pointed to by the return of
malloc
and refers to that block of 11 characters. All memory requested bymalloc
must be freed byfree
and what you've asked for withmalloc
is that block of 11 characters so you can't free part of them in the same way that if you buy a loaf of bread you can't return half of it to have bought half!However, you can reallocate the memory, for that the function is used
realloc
: