I am reading a file of floating point numbers and then sorting them. When I use my following sort and swap functions with 1 million numbers, I am successfully able to sort the numbers. However, when I try to sort 100 million numbers, I get a segmentation fault. I am not sure why because I am dynamically allocating memory. How would I be able to handle more than 1 million numbers?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void swap(float *a, float *b, size_t n) {
size_t numbytes;
size_t sz = sizeof(float);
void *temp = NULL;
numbytes = n * sz;
if (numbytes == 0){
exit(EXIT_FAILURE);
}
temp = malloc(numbytes);
memcpy(temp, a, numbytes);
memcpy(a,b,numbytes);
memcpy(b,temp,numbytes);
free(temp);
}
void radixSort(float array[], size_t count) {
int numOfZero = 0;
float a[count];
float *b = a;
for (uint32_t radix=1; radix; radix<<=1) { //unsigned int 32 bit
uint32_t *arrayToInt = (uint32_t *)array;
int zeroCount=0;
int oneCount=0;
numOfZero=0;
for (int j=0; j < count; ++j)
numOfZero += !(arrayToInt[j]&radix);
oneCount=numOfZero;
for (int j=0; j < count; ++j)
if (arrayToInt[j]&radix){
b[oneCount]=array[j];
++oneCount;
}
else{
b[zeroCount]=array[j];
++zeroCount;
}
swap(b,array,count);
}
if (numOfZero < count){
memcpy(b+(count-numOfZero), array, numOfZero*sizeof(float));
for (int d=0,j=count-1;j>=numOfZero;j--,d++)
b[d]=array[j];
memcpy(array, b, count*sizeof(float));
}
}
int main(int argc, char *argv[]) {
int fd;
float num;
size_t nr;
int eleNum = 0;
fd = open(argv[1], O_RDONLY);
if (fd == -1){
perror("Error opening file");
exit(EXIT_FAILURE);
}
struct stat st;
fstat(fd, &st);
off_t size = st.st_size;
for (int j = 0; j < size/4; j++){
eleNum++;
}
float array[eleNum];
for (int i = 0; i < eleNum; i++){
nr = read(fd, &num, sizeof(float));
if (nr == -1){
perror("Error reading file");
exit(EXIT_FAILURE);
}
array[i] = num;
}
radixSort(array, eleNum);
close(fd);
return 0;
}