hello everyone...
m writin a code that will take data frm stdin from user which can b of indefinte size..
but i cant make use of static arrays....and even calloc and malloc is not working properly...what sud i do???


thanks for help...

Post your code or do you think we are mind readers?

malloc() and calloc() work perfectly -- its your code that doesn't work for some unknown reason.

Edited 5 Years Ago by Ancient Dragon: n/a

char *ch1,*ch2;
char ch;
ch1= (char *)malloc(1);
ch= getchar();
*ch1=ch;
while(ch!=EOF){
ch1= (char *)realloc(ch1,1);
ch1++;
ch=getchar();
*ch1=ch;
}

I don't like that your realloc'ing ch1 and then incrementing the pointer ch1. To me this seems like a recipe for disaster

Your program doesn't work because it is destroying the ch1 pointer on each loop iteration. You can't increment ch1, just leave it along after the initial allocation with malloc(). Use a different pointer or integer.

Another problem is that your program is very very slooooow -- malloc() and realloc() are rather time consuming, so instead of allocating just one character at at time you should allocate a block of characters, then when the block is filled up you should call realloc() to increase the block

#define BLOCK_SIZE 80
int block_size = 0;
int current_spot = 0;
char* c1 = 0;
char c;

while( (c = getchar()) != EOF )
{
   if( block_size == current_spot)
   {
       c1 = realloc(c1, block_size + BLOCK_SIZE); 
       block_size += BLOCK_SIZE;
   }
   c1[current_spot] = c;
   ++current_spot;
}

Edited 5 Years Ago by Ancient Dragon: n/a

char *ch1,*ch2;
char ch;
ch1= (char *)malloc(1);
ch= getchar();
*ch1=ch;
while(ch!=EOF){
ch1= (char *)realloc(ch1,1);
ch1++;
ch=getchar();
*ch1=ch;
}

hi,

this is ma code...for taking data from user from stdin as many line as he enters
its taking jst 5 line frm stdin then its throwing segmentation user.

ny help

thanks

In the simplest terms...Don't do this, its wrong.

ch1= (char *)realloc(ch1,1);
ch1++;

Edited 5 Years Ago by gerard4143: n/a

This question has already been answered. Start a new discussion instead.