Edited by Sinipull, 01 December 2009 - 06:18 AM.
Problem with dynamic memory allocation in C
Started by Sinipull, Nov 11 2009 10:28 AM
3 replies to this topic
#1
Posted 11 November 2009 - 10:28 AM
Okay, so i need to get character array from std input with scanf. The character array size isn't specified and must hold whatever sized input (computer memory is the limit...). Any ideas?
|
|
|
#2
Posted 11 November 2009 - 01:20 PM
char* line;
char c;
int i=0;
line=calloc(1, sizeof(char));
do
{
c=getchar();
line=realloc(line, sizeof(char)*(i+1));
line[i]=c;
i++;
}
while(c!='\n');
line[i]='\0';
Something like this. I didn't test it. ;D
Obviously you can use scanf instead of getchar().
#3
Posted 11 November 2009 - 05:17 PM
Quote
line=realloc(line, sizeof(char)*(i+1));
I would recommend something like the following:
char *tmp = realloc(line, sizeof(char)*(i+1));
if(!tmp) {
//reallocation failed
free(line);
printf("Out of memory!\n");
}
else
line = tmp;
sudo rm -rf /
#4
Posted 12 November 2009 - 03:42 AM
Thanks! Helps me a lot.


Sign In
Create Account


Back to top









