(1) Isnt this going to break, as the string needs one more byte for the ending zero byte?
Yes, the code is wrong as strcpy don't know of the allocated size and would write beyond array boundaries. It won't crash nevertheless in most cases cause a string termination normally is a read-only byte *and* allocation happens in chunks
(2) Would it not make more sense to have a method that does this, correctly, in one place,
rather than sixteen separate occurrences of these two lines?
By using std::string instead of char arrays, the copies wouldn't alllocate storage for the internal buffer but have a reference to the original source buffer for any copy.
>>>> Add(new char[ strlen(gridChars) ]);
As Infinity told, the Add function could handle the copying. Generally, don't pass pointers from outside into a member function. Always try to allocate at the same level as you will free the memory (in your sample most likely in the destructor, hence it should be the constructor or the Add member function where the 'new' should be called).
Regards, Alex
Main Topics
Browse All Topics





by: Infinity08Posted on 2007-08-27 at 10:53:16ID: 19777195
>> (1) Isnt this going to break, as the string needs one more byte for the ending zero byte?
rs);
It will indeed as far as I can see (assuming that gradCharsSeen behaves predictably).
>> (2) Would it not make more sense to have a method that does this, correctly, in one place,
rather than sixteen separate occurrences of these two lines?
imo, it would make more sense to do something like this instead :
gridCharsSeen->Add(gridCha
Looks nicer, is a lot clearer, and the memory allocation is hidden inside the Add method. Then just add a proper destructor to deal with the allocated memory, and presto : the interface looks a lot cleaner imo.