views:

71

answers:

1

I am using the cstdio (stdio.h) to read and write data from binary files. I have to use this library due to legacy code and it must be cross-platform compatible with Windows and Linux. I have a FILE* basefile_ which I use to read in the variables configLabelLength and configLabel, where configLabelLength tells me how much memory to allocate for configLabel.

unsigned int configLabelLength; // 4 bytes
char* configLabel = 0;          // Variable length

fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_);
configLabel = new char[configLabelLength];
fread(configLabel,1, configLabelLength,baseFile_);

delete [] configLabel; // Free memory allocated for char array
configLabel = 0; // Be sure the deallocated memory isn't used

Is there a way to read in configLabel without using a pointer? For example is there a solution where I can use the c++ vector library or something where I do not have to worry about pointer memory management.

+4  A: 

Just do:

unsigned int configLabelLength; // 4 bytes*
fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_);

std::vector<char> configLabel(configLabelLength);
fread(&configLabel[0], 1, configLabel.size(), baseFile_);

The elements in a vector are contiguous.


* I assume you know that unsigned int isn't necessary always 4 bytes. If you pay attention to your implementation details that's fine, but it'll be a bit easier if you adopt Boost's cstdint.hpp and just use uint32_t.

GMan
@Gman...that assumption is correct. Due to legacy code and that other less-skilled/experienced users will be using this code, I am trying my best to keep the code readable. I really like boost and implement it else where, but I am tentative to implement boost for variables. Our ICD specifically uses the term `unsigned int`, so I want to try to match the ICD for other users. :p
Elpezmuerto
Big agreement with your 4 bytes comment. Binary file and network code should always use objects with specified sizes, alignments and byte order. Forex, I use a C++ struct named le_uint32_t to make code work on PowerPC with Intel binary formats.
Zan Lynx