emscripten-core / emscripten-core/emscripten
C stdlib function fread breaks with bytes with leading 1s
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
When reading a bytefile with fread the following strange thing happens.
```c
// fread_bug.c
#include
#include
int main(int argc, char **argv) {
int8_t buffer[10];
int64_t num_elems_read = (int64_t)fread(buffer, 1, 10, stdin);
for (int i = 0; i < 10; i++) {
printf("%d element is : %d\n", i, buffer[i]);
}
return 0;
}
```
And with the following python code to write a byte array
```python
#make_bin_file.py
newFile = open("file.bin", "wb")
byty = [0, 1, 2, 234, 4, 5, 6, 7, 8, 9]
nba = bytearray(byty)
newFile.write(nba)
```
Assuming we do the following
```bash
gcc fread_bug.c
python3 make_bin_file.py
./a.out < file.bin
```
gives the following result
```
0 element is : 0
1 element is : 1
2 element is : 2
3 element is : 234
4 element is : 4
5 element is : 5
6 element is : 6
7 element is : 7
8 element is : 8
9 element is : 9
```
However when we use Emscripten like so
```bash
emcc fread_bug.c
python3 make_bin_file.py # Not neccesary if done in previous step
node a.out.js < file.bin
```
We get the following output
```
0 element is : 0
1 element is : 1
2 element is : 2
3 element is : 239
4 element is : 191
5 element is : 189
6 element is : 4
7 element is : 5
8 element is : 6
9 element is : 7
```
It seems as though fread always breaks when any leading bit in a byte to fread has a 1 (concluded this from more experimentation), in which case 3 bytes are misread, before going back to reading bytes normally.
I am working on a Mac. with
emcc (Emscripten gcc/clang-like replacement) 2.0.7
Contributor guide
Assessment
This issue has not been assessed yet.