0

In C (with gcc), I used to have some data structures that were an array with some extra information:

struct song {
    uint tempo;
    uint key;
    note play[0]; // or play[] depending on compiler flavour
};

Iirc, that's dubbed a "flexible array" (http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html#Zero-Length) I could then allocate a song of N notes with malloc(sizeof(song)+N*sizeof(note)) at run-time. To what extent is that supported in g++, if I don't intend to use vectors this time, nor to introduce a useless note* pointer in song ?

4

2 Answers 2

4

Even in C, this is undefined and non-portable. GCC knowingly lets you get away with it, but other implementations may not. This is because you are accessing an array beyond its bounds.

This "trick" is precisely as valid in C++ as it is in C. That is, feel free to use it in GCC where the GCC documentation says it's supported, but it'll never be "well-defined, valid C++".

1
  • 2
    I vaguely remember that there was actually a pretty huge bug in some widely used OSS app due to reliance of out-of-bound pointer access. This may seem safe but it most decidedly is not, and the optimiser can pull some very funky stunts that render such code dangerous. Feb 17, 2013 at 13:45
-1

there is no other way than using a fixed length or a note* because the compiler must know how long your song-structs are, and every struct has the same lenght.

so you have to use a note* or a vector

1
  • I worry that this answer rejects or misses the premise of the flexible array hack. Feb 17, 2013 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.