I am getting a segmentation fault on the below snippet, only when I go above a text file in the range of 80-100kb. It will read smaller files of text but otherwise segmentation 11
.
int main(int argc, char* argv[])
{
FILE* file;
if (argc != 2 || (file = fopen(argv[1], "r")) == NULL) {
printf("Invalid command\n");
exit(EXIT_FAILURE);
}
int capacity = 5;
char* buffer = malloc(capacity);
int length = 0;
char ch;
while ((ch = getc(file)) != EOF) {
if (length >= capacity)
capacity *= 2;
buffer = realloc(buffer, capacity);
buffer[length++] = ch;
}
buffer[capacity] = '\0';
printf("%d\n", length);
printf("%s", buffer);
free(buffer);
fclose(file);
return EXIT_SUCCESS;
}
What type of problems could I be overlooking and how can I improve this code to more efficiently achieve what I am trying to get out of it (which is to read an unknown size of text from a file and output it as a string, also dynamically allocating memory by doubling array size)?