Hello there,
I am trying to implement a custom gets function which would allow me to read a string so as to avaoid the pitfalls associated with the C version of 'gets'.

Well...I have been able to get some breakthrough into it. What my function does it that it keeps on extending the buffer (to hold the string) size by 16 if the user enters a string longer than 16 until it encounters the '\n' character. Im doing a char by char read using getchar and i check for the '\n' character and for the number of chars entered as of yet.

So if the user string is more than 4(size of the original buffer) but less than 16, it works fine though it only displays the first 4 chars..but if the user string is >16 then issues do arise.

Im wondering why...the seg fault occurs at the line preceded by an arrow-head in the program below

Code:
#include <stdio.h>
#include "mygets1.h"

int main()
{
    char  b1[] = "ABCD";
    char  b2[] = "LMNO";
    char  b3[] = "ZYXW";
    
    puts(b1);
    puts(b2);
    puts(b3);
    putchar('\n');
    
    puts("Enter some characters:");
    mygets(b2);

    putchar('\n');
    puts(b1);
    puts(b2);
    puts(b3);
    
    return(0);
}

//mygets1.h - - -  my gets function 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mygets(char str[]); //func prototype

char* mygets(char str[])

{
    //    char *str;
    unsigned int i = 0;
    int bffr_fl = 1; //flag to check the if user input exceeds 4 chars
    int mul_factor = 1; //how many 16-char wide chunks do we need?
    int tmp; //holder for the multiplication (see below)
    size_t sze = strlen(str);

    while ((str[i] = getchar()) != '\n'){
        i++;
        if(i >= sze && bffr_fl) {
                str = realloc(str,16*sizeof(char));//increase the size to 16
                bffr_fl = 0;
                mul_factor++;
        }
        else if(i % 16 == 0) {
           tmp = 16*mul_factor;         
-->       str = realloc(str,tmp*sizeof(char));//add another 16-wide chunk  to the tail
            mul_factor++;
        }
    }
    printf("the user pressed enter at position number %d\n",i);
    str[i] = '\0'; //append a trailing null after the last char
    return str;
}
Id be pleaed if you could come up with some suggestions. Like what I plan now is to use something else for the first extension of the string and then start using realloc iteratively.