As first steps in C, I'm trying to write a program that reads from stdin into an array allocated on the free store, until an exclamation mark !
is entered. The array should be extended to prevent overflow.
Here is what I've written:
#include <stdio.h>
#include <stdlib.h>
char* increase_buffer_size(char *buff_ptr, size_t multiplier);
//==================================================================
int main () {
// initial buffer size
size_t buffer_size = 32;
// allocate 32 bytes of heap memory
char *buffer_pointer = (char*) malloc(buffer_size);
// input loop variables
char input_var;
size_t counter = 0;
char sentinel = '!';
// input loop
printf("Type input\n>>");
while (input_var = getchar()) {
// check termination condition
if (input_var == sentinel) break;
// check capacity and double it if maximum is reached
if (counter == buffer_size - 1) buffer_pointer = increase_buffer_size(buffer_pointer, buffer_size *= 2);
// populate buffer
buffer_pointer[counter++] = input_var;
}
getchar();
// print input values
printf("Buffer content: \n");
for (auto i = 0; i < counter; ++i) printf("%c %c", buffer_pointer[i], ' ');
getchar();
}
//==================================================================
char* increase_buffer_size(char *buff_ptr, size_t new_size) {
char* new_ptr = (char*) realloc(buff_ptr, new_size);
return new_ptr;
}
As I already mentioned these are my first steps in C, so I was wondering:
Is the above code written in accordance with C conventions?
Is there anything that can be skipped or written better?