[ create a new paste ] login | about

Link: http://codepad.org/TDsKiiIA    [ raw code | output | fork ]

nilukush - C, pasted on Apr 16:
#include <stdio.h>  /* For size_t */
#include <limits.h>

/* 
   Reads at most size characters into the array. 
   Stops if a newline or EOF is encountered. 
   The newline is not included in the array. 
   The array is always terminated by '\0'. 
   Returns length of the string. 
   Please note that memory allocation is callers responsibility. 
   pptr should have space for size+1 characters. 
*/ 

size_t input(char *pptr, size_t size) 
{   size_t len = 0;

    while(size > len) 
    {   int ch;
        ch = getchar(); 
        if(ch == '\n' || ch == EOF) break;
        printf("\nCurrent len : %d, ", len);
        printf("Before : %c, ", *pptr);
        *(pptr++) = (char)ch;
        printf("After : %c, ", *(pptr-1));
        ++len;
    } 
    *pptr = '\0'; 
    return len; 
}

int main(void)
{   int size = INT_MAX;
    char *pptr = (char*)malloc(size);
    printf("\nSize : %d", size);
    printf("\nRead string from keyboard : ");
    input(pptr, size);
    return 0;
}


Output:
1
Segmentation fault


Create a new paste based on this one


Comments: