0

I've met a situation that I think it is undefined behavior: there is a structure that has some member and one of them is a void pointer (it is not my code and it is not public, I suppose the void pointer is to make it more generic). At some point to this pointer is allocated some char memory:

void fooTest(ThatStructure * someStrPtr) {
    try {
        someStrPtr->voidPointer = new char[someStrPtr->someVal + someStrPtr->someOtherVal];
    } catch (std::bad_alloc$ ba) {
        std::cerr << ba.what << std::endl;
    }
    // ...

and at some point it crashes at the allocation part (operator new) with Segmentation fault (a few times it works, there are more calls of this function, more cases). I've seen this in debug.

I also know that on Windows (my machine is using Linux) there is also a Segmentation fault at the beginning (I suppose that in the first call of the function that allocates the memory).

More, if I added a print of the values :

std::cout << someStrPtr->someVal << " " << someStrPtr->someOtherVal << std::endl;

before the try block, it runs through the end. This print I've done to see if there is some other problem regarding the structure pointer, but the values are printed and not 0 or negative.

I've seen these topics: topic1, topic2, topic3 and I am thinking that there is some UB linked to the void pointer. Can anyone help me in pointing the issue here so I can solve it, thanks?

Community
  • 1
  • 1
sop
  • 3,445
  • 8
  • 41
  • 84

2 Answers2

3

No, that in itself is not undefined behavior. In general, when code "crashes at the allocation part", it's because something earlier messed up the heap, typically by writing past one end of an allocated block or releasing the same block more than once. In short: the bug isn't in this code.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2

A void pointer is a perfectly fine thing to do in C/C++ and you can usually cast from/to other types

When you get a seg-fault while initialization, this means some of the used parameters are themselves invalid or so:

  • Is someStrPtr valid?
  • is someStrPtr->someVal and someStrPtr->someotherVal valid?
  • Are the values printed is what you were expecting?
  • Also if this is a multuthreaded application, make sure that no other thread is accessing those variables (especially between your print and initialization statement). This is what is really difficult to catch
Moataz Elmasry
  • 2,509
  • 4
  • 27
  • 37
  • So what was the issue? – Moataz Elmasry Sep 19 '16 at 18:51
  • Not sure yet, but you are answering the question: "A void pointer is a perfectly fine thing to do in C/C++". The other values seem to be valid. I've added `if (!someStrPtr) std::cout << "KO" << std::endl;` (and for the others) and none of the KO was printed – sop Sep 20 '16 at 07:05