P
paytam
hi all
can you tell me what's the wrong with this code?
I use gcc compiler,but when I wanted to use
gets() function in my code but it takes a dangerous warning(the gets
function is dangerous
and should not be used),I don't know why.Any way,I decided to write my
own gets()
function,but now it take segmentation fault error.Please help me
thanks
THIS IS THE CODE:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * getstring()
{
int k=1,j=0,i;
char ch;
char *source=malloc (sizeof(char)*k);
if(!source)
{
printf("\n\nCan not allocate sufficent memory\n\n");
exit(1);
}
else{
while((ch=getchar())!='\n')
{
if(j==k)
{
realloc(source,(k*=2));
if(!source)
{
printf("\ncan not allocat sufficiant memory\n");
exit(1);
}//end if
}//end if
*(source+j)=ch;
j++;
}//end while
*(source+j)='\0';
//Here it shows correctly
printf("\n\n\n\n\nThis is what you typed :%s\n",source);
}//end of else
return source;
}
void main()
{
char *st;
printf("Enter a string: ");
/*If you want to see the warning gets message uncomment here
gets(st);
*/
//I forgot here or next command generate the segmentation fault
strcpy(st,getstring());
printf("\n\n\n\n\nThis is what you typed :%s\n",st);
}
can you tell me what's the wrong with this code?
I use gcc compiler,but when I wanted to use
gets() function in my code but it takes a dangerous warning(the gets
function is dangerous
and should not be used),I don't know why.Any way,I decided to write my
own gets()
function,but now it take segmentation fault error.Please help me
thanks
THIS IS THE CODE:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * getstring()
{
int k=1,j=0,i;
char ch;
char *source=malloc (sizeof(char)*k);
if(!source)
{
printf("\n\nCan not allocate sufficent memory\n\n");
exit(1);
}
else{
while((ch=getchar())!='\n')
{
if(j==k)
{
realloc(source,(k*=2));
if(!source)
{
printf("\ncan not allocat sufficiant memory\n");
exit(1);
}//end if
}//end if
*(source+j)=ch;
j++;
}//end while
*(source+j)='\0';
//Here it shows correctly
printf("\n\n\n\n\nThis is what you typed :%s\n",source);
}//end of else
return source;
}
void main()
{
char *st;
printf("Enter a string: ");
/*If you want to see the warning gets message uncomment here
gets(st);
*/
//I forgot here or next command generate the segmentation fault
strcpy(st,getstring());
printf("\n\n\n\n\nThis is what you typed :%s\n",st);
}