0

I have this function for reading text from files:

uintmax_t ResourcePack::getText(const string& file, char** data)
{
    *data = new char[static_cast<size_t>(size) + 1];
    fseek(_fileDescriptor, static_cast<long>(begin), SEEK_SET);
    fread(*data, static_cast<size_t>(size), 1, _fileDescriptor);
    *data[size] = '\0';
}

FILE* _fileDescriptor, uintmax_t size and uintmax_t begin are get in other code, not important here, but with correct values.

fseek and fread lines work fine. Actually, I have the file content in *data, but when the last line is executed, I got the access violation.

Why I can write into *data using fread, but not using *data[size] = '\0'?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
danikaze
  • 1,550
  • 2
  • 16
  • 34
  • 9
    Operator precedence - you want `(*data)[size]`, not `*data[size]`. – Paul R Dec 17 '12 at 22:05
  • 3
    As @PaulR said... Generally I prefer to store a temporary `char*` variable and work with that in a function, then store it via the `char**` prior to returning. That way I avoid the extra syntax guff that can lead to errors and/or sore eyes. =) – paddy Dec 17 '12 at 22:09
  • 0xCC means you've read [uninitialized memory](https://stackoverflow.com/q/370195/995714) – phuclv Oct 17 '17 at 04:34

2 Answers2

5

You are having problems with operator precedence - you want (*data)[size], not *data[size].

Paul R
  • 208,748
  • 37
  • 389
  • 560
3

Your problem is the precedence of operators * and []. *data[size] means to access the nth char* in data, and then dereference its first character, not to get the nth character of the array pointed to by data.

You want (*data)[size] instead to perform the operations in the correct order.

EDIT: Since this is C++ you'd be better off using char*& to eliminate these sorts of problems, or much better off using vector and letting the standard library manage your memory for you!

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • I usually use std containers, but for this situation, a raw pointer is better in my case ;) I just forgot operators precedence :P – danikaze Dec 17 '12 at 22:45