Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack around the variable 'dim'(not an array) was corrupted

I'm trying to read from a binary file, using fstream, some data I have previously written there.

The problem is that after getting to the end of the function the message in the subject is shown

The code is the following:

ifstream in("contrib.bin", ios::in | ios::binary );

char *nume, dim;
in.read((char*)&dim, sizeof(int));
nume = new char[dim + 1];
in.read(nume, dim);
nume[dim] = '\0';
double imp;
in.read((char*)&imp, sizeof(double));

delete [] nume;

Now, I've done my homework and looked for this issue, but the other people who faced it had arrays, whereas my variable is a simple char.

Can someone point me to the right direction, please?

like image 670
Cristina_eGold Avatar asked Aug 02 '26 08:08

Cristina_eGold


1 Answers

The code

char dim;
in.read((char*)&dim, sizeof(int));

defines a 1 byte char then reads sizeof(int) bytes (which is likely to be greater that 1) into it. This is invalid and may corrupt your stack.

If you need to read sizeof(int) bytes, declare dim as int. Otherwise, change the number of bytes you read to 1. It'd be best if you also used sizeof(dim) to ensure that you only read as many bytes as you've provided storage for:

in.read((char*)&dim, sizeof(dim));
like image 100
simonc Avatar answered Aug 03 '26 23:08

simonc