Readline function implementation

I've created my own readline function, which reads a variable-size line from the standard input. It's been some time I've not practice much C or C++. Here's my implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
char* readline(){
    
    size_t n = 10;
    char* final = malloc(n * sizeof(char));
    final[0] = '\0';
    char* tmp; // used for allocating memory temporarily

    // constant buffer size used to store the read characters
    // before storing them in the final buffer
    char buf[10]; 
    
    while(fgets(buf, 10, stdin) != NULL) {

	if(buf[strlen(buf) - 1] == '\n') {
	    
	    if(strlen(buf) > 1) {
		
		if((n - strlen(final)) < (strlen(buf) + 1)) {

		    n = strlen(final) + strlen(buf); // -1 because buf contains also \n at the end

		    tmp = malloc(n * sizeof(char));

		    for(int i=0; i <= strlen(final); ++i)
			tmp[i] = final[i];

		    free(final);
		} else {
		    tmp = final;
		}
		    
		int i, j;
		for(i = strlen(final), j = 0; j <= (strlen(buf) - 2); ++i, ++j)
		    tmp[i] = buf[j];

		tmp[i] = '\0';

		final = tmp;
	    }
	    	    
	    break;
	    
	} else { // we need to reallocate memory
	    
	    if((n - strlen(final)) < (strlen(buf) + 1)) {

		n *= 2;
		tmp = calloc(n, sizeof(char));
		
		// if this happened at least once, copy all the contents of final to tmp
		// copy also the '\0' at the end
		for(int i = 0; i <= strlen(final); ++i) 
		    tmp[i] = final[i];

		free(final);
		
	    } else {
 		tmp = final;		
	    }	    

	    // Starts inserting from the '\0' char
	    // Insert also the '\0' at the end
	    // printf("strlen(tmp) = %lu\n", strlen(tmp));
       	    for(int i = strlen(tmp), j = 0; j <= 9; ++i, ++j)
		tmp[i] = buf[j];

	    final = tmp;

	}
	
    }

    return final;
}


**Questions**

1. Is it correct? Is memory allocation well-performed? Of course the user must then deallocate the memory.

2. Can I improve it somehow?
Topic archived. No new replies allowed.