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"
Code:
int main(){
int x=10, y=0;
char *word;
word=(char *) malloc(x*sizeof(char));
while((word[y]=getchar())!='\n'){
y++;
if(x==y){
x*=2;
word=(char *) realloc(word,(x*sizeof(char)));
}
}
word[y]='\0';
printf("%s\n",word);
}
this code works fine, my problem comes when i want to free the memory allocated that isn't being used...
[ 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));
strcpy(dog,word);
free(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