0

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...

3
Contributors
8
Replies
10
Views
6 Years
Discussion Span
Last Post by amir malik
0

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 by Ancient Dragon: n/a

0

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;
}

0

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

0

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 by Ancient Dragon: n/a

0

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

0

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

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

Edited by gerard4143: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.