hi, first of all, english isn't my native languaje so plz excuse me if i write something wrong
i made a program that allow me to work with a "dynamic array"
this code works fine, my problem comes when i want to free the memory allocated that isn't being used...
int x=10, y=0;
word=(char *) malloc(x*sizeof(char));
word=(char *) realloc(word,(x*sizeof(char)));
[ I ][ I ][ I ][ I ][ I ][ I ][ I ][ \0 ][O][O][O][O][O]
i thought in some possible solutions but none of them seems perfect.
1: Use free(), giving the array pointer as parameter and trying to move it to where the array ends..
[ I ][ I ][ I ][ I ][ I ][ I ][ I ][ \0 ][O][O][O][O][O] <-- i tried to "move" the pointer to the position next to \0 and use free() to release the memory.. but this didn't work, free doesn't allow the use of a pointer plus something (example: free(word+1) )
i don't know why this doesn't work and i would really appreciate if someone can explaint it to me...
2.- I read that realloc allows to increase or decrease space, so i thought that using it again over the pointer would reallocate the memory correctly.. but the problem is that i don't really know what happens with the memory that isn't reallocated
word=(char *) realloc(word,(strlen(word))*sizeof(char)); <-- that's the code
3.- the third option is to create another array and use strlen to allocate the exact space and then free the other array
char *dog = (char *) malloc( (sizeof(char)) * strlen(word));
seems good to me too, but what if i don't have enough memory to create another array? (assuming that the user writes one billion characters :zippy)
the second and third options works (i think 2 is the best)
but i would be grateful if anyone can give me an opinion