So I'm trying to read in from stdin a byte at a time. Each iteration of the while loop I am trying to reallocate the buffer, but I don't want to use realloc. This is what I've tried:
char tempChar = '\0';
char *buffer;
int bufferSize = 0;
buffer = (char*) malloc(sizeof(char));
while((tempChar = getc(stdin)) != EOF)
{
buffer[bufferSize] = tempChar;
bufferSize++;
char *temp = buffer;
buffer = (char*)malloc(sizeof(char)*bufferSize);
memcpy(buffer, temp, sizeof(temp));
free(temp);
}
buffer[bufferSize] = '\0';
I get a segmentation fault. Any idea why that happens?
EDIT: Ok I fixed the two bugs like other people have said. Here is the fixed version:
char tempChar = '\0';
char *buffer;
int bufferSize = 1;
int count = 0;
buffer = malloc(sizeof(char));
while((tempChar = getc(stdin)) != EOF){
buffer[count] = tempChar;
count++;
if(count >= bufferSize){
bufferSize *= 2;
char *temp = buffer;
buffer = malloc(sizeof(char)*bufferSize);
memcpy(buffer, temp, count);
free(temp);
}
}
buffer[count - 1] = '\0';