I try to realise an external merge sort (wiki) and I want to open 2048 ifstreams and read data to personal buffers.
ifstream *file;
file = (ifstream *)malloc(2048 * sizeof(ifstream));
for (short i = 0; i < 2048; i++) {
itoa(i, fileName + 5, 10);
file[i].open(fileName, ios::in | ios::binary); // Access violation Error
if (!file[i]) {
cout << i << ".Bad open file" << endl;
}
if (!file[i].read((char*)perfile[i], 128*4)) {
cout << i << ". Bad read source file" << endl;
}
}
But, it crashes with
Unhandled exception at 0x58f3a5fd (msvcp100d.dll) in sorting.exe: 0xC0000005: Access violation reading location 0xcdcdcdfd.
Is it possible to use so much opened ifstreams?
Or maybe it is very bad idea to have 2048 opened ifstreams and there is a better way to realize this algorithm?
Arrays of non-POD objects are allocated with
new, not withmalloc, otherwise the constructors aren’t run.Your code is getting uninitialized memory and “interpreting” it as
ifstreams, which obviously results in a crash (because the constructor of the class hasn’t been run not even the virtual table pointers are in place).You can either allocate all your objects on the stack:
or allocate them on the heap if stack occupation is a concern;
(although you should use a smart pointer here to avoid memory leaks in case of exceptions)
or, better, use a
vectorofifstream(requires header<vector>):which do not require explicit deallocation of its elements.
(in theory, you could use
mallocand then use placementnew, but I wouldn’t recommend it at all)… besides, opening 2048 files at the same time doesn’t feel like a great idea…