Reputation: 361
I am trying to use realloc function to store input characters in a dynamically array. Everything goes fine when I use it without calling free method to release the memory after usage. But when I use it with free method runtime error comes. Here is my code snippet.
int main(){
char *message ;
int len = 0 ;
char c ;
while((c=getchar()) != '\n'){
message = realloc(message,(len+1)*sizeof(char)) ;
message[len++] = c ;
}
message = realloc(message, (len+1)* sizeof(char));
message[len]='\0' ;
printf("Message is %s\n",message);
free(message) ;
return 0 ;
}
Can anyone figure out this. As i need to use both method together.. Thanks!!!!
Upvotes: 1
Views: 179
Reputation: 490048
Though it may not be causing the problem you're seeing, X = realloc(X, newsize);
is a timebomb waiting to explode. realloc
can return a null pointer and leave your existing data unchanged if it fails to allocate the new chunk you've asked for. When/if it does that, this will overwrite the existing pointer with NULL, leaking the memory you've previously allocated (and failing to allocate more).
Though it's probably not causing the problem either, I'd also recommend (strongly) against using realloc
to increase your allocation one character at a time. That's horribly inefficient. I'd start with a block of, say, 32 or 64 characters, and increase the allocation by some factor (say, 1.5) each time you run out of space. This way you can deal with greatly different lengths of input without a huge number of calls to realloc.
Edit: looking at it, the real problem probably that you haven't initialized your pointer properly before the initial call to realloc
. If you pass something other than a NULL pointer, it expects what you're passing to be a valid pointer you got from malloc
/calloc
or a previous call to realloc
.
int main(){
char *message ;
int len = 0 ;
char c ;
while((c=getchar()) != '\n'){
message = realloc(message,(len+1)*sizeof(char)) ;
message[len++] = c ;
}
message = realloc(message, (len+1)* sizeof(char));
message[len]='\0' ;
printf("Message is %s\n",message);
free(message) ;
return 0 ;
}
At least for me, this runs without any error messages.
Upvotes: 1