XAgent-Smith

Getlinefunction-Allocate- memory on runtime

Sep 25th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. /*Author-XAgent Smith*/
  2. /*Date:Step 25,2018*/
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. /*Start of getln fuction*/
  6. void *reallo_c(char  ** c,size_t size,size_t len)
  7. {
  8.    char *k=NULL;
  9.    short i=0;
  10.    k=(char*)malloc(size*sizeof(char));
  11.   while((( 0<=(len--)&&*((*c)+i)!='\0')?*(k+i++)=*(*(c)+i) : 0));
  12.    free(*c);
  13.    return k ;
  14. }
  15. char *getln(void)
  16. {
  17.     //Initializing variables and pointers
  18.     const size_t sizeIncrement=5;
  19.     char *buffer=(char*)malloc(5*sizeof(char));
  20.     char *currentposition=buffer;
  21.     size_t max_length=sizeIncrement;
  22.     size_t length=0;
  23.  static size_t L=0;
  24.     char character;
  25.     /*getting inputes*/
  26.     while(1)
  27.     {  
  28.         character=fgetc(stdin);//getting character from stdin file
  29.         if(character=='\n') break;
  30.    
  31.         if(length>=max_length-1)
  32.         {
  33.             /*Allocating memory for next increment extra chararcter*/
  34.             char *newbuffer=reallo_c(&buffer,(max_length+sizeIncrement),L-1);
  35.             max_length+=sizeIncrement;
  36.             if(newbuffer==NULL)
  37.             {
  38.                 free(buffer);
  39.                 return NULL;
  40.             }
  41.             currentposition=newbuffer+L;
  42.             buffer=newbuffer;
  43.         }
  44.         *(currentposition++)=character;
  45. L++;
  46.         length++;
  47.     }  
  48.     *currentposition='\0';
  49.     return buffer;
  50.     /*End of getln function call*/
  51. }
  52.  
  53. /*Start of main*/
  54. int main()
  55. {  
  56.     //calling getln();
  57.     printf("%s\n",getln());
  58.     return 0;
  59.     /*End of main*/
  60. }
Add Comment
Please, Sign In to add comment