I have troubles allocating enough memory to read an input file
containing 1 million data (the file size is 19MB), I tried to use
malloc(sizeof(buffer_size)*1000000) to allocate continuous memory to
keep that data, but it still gives me segmentation fault. in such case
what should I do?
regards,
Here is a VERY CRUDE little program that you can take a look at:
_______________________________________________________________________
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define BUFSZ 4096
#define DEPTH 1024
#define DELIM ","
int compare(void const* a1, void const* a2) {
long n1 = *((long const*)a1);
long n2 = *((long const*)a2);
if (n1 < n2) return -1;
if (n1 > n2) return 1;
return 0;
}
int main(void) {
FILE* file = fopen("data.txt", "r");
if (file) {
long* numbers = malloc(sizeof(*numbers) * DEPTH);
size_t count = 0;
if (numbers) {
char data[BUFSZ + 1] = { '\0' };
if (fgets(data, BUFSZ, file)) {
size_t delimsz = strlen(DELIM);
char* current = data;
char* stopped = NULL;
char* end = data + strlen(data);
do {
numbers[count] = strtol(current, &stopped, 10);
if (errno != ERANGE) {
count++;
} else {
fprintf(stderr, "range error!");
}
current = stopped + delimsz;
} while (count < DEPTH && current < end);
} else {
fprintf(stderr, "error reading from the file!");
}
} else {
fprintf(stderr, "error allocating memory!");
}
if (fclose(file)) {
fprintf(stderr, "error closing the file!");
}
if (numbers && count) {
size_t i;
qsort(numbers, count, sizeof(long), compare);
for (i = 0; i < count; ++i) {
printf("%d\n", numbers
);
}
free(numbers);
}