Jump to content

Problem with dynamic memory allocation in C

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
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?

Edited by Sinipull, 01 December 2009 - 06:18 AM.


#2
psam

psam

    Learning Programmer

  • Members
  • PipPipPip
  • 34 posts

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
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts

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
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
Thanks! Helps me a lot.