Strange segmentation violation

Dear Root support, I’m working on a macbook and run in a strange segmentation violation.
The problem seems not related to root (the test program isn’t compiled against it and doesn’t uses it), but after brief contact with Axel I hope it is ok to post it here.
Perhaps it should be in cling support, if the moderator thinks this is better place feel free to move…

Last week though I got into the following segmentation violation in an isolated test program:

-declaring an array of floats (on the heap) as
float * Ebins_var= new float(binEdges.size()); and filling the array gives a segfault. It seems new is not assigning any memory! *
-declaring the same on the stack: double Ebins_var[binEdges.size()]; and filling works fine. The only thing that differs is the method of declaration.

I stripped the problem down to a minimal macro (which is not compiled against root). The macro doesn’t seem to give a segfault when I run it remotely. to make the post not too lengthy, I put all information (macro, output, makefile, output with valgrind, environmental variables) in attachment.
I should still mention: I work on macbook, OS 10.8.5. XTools 5.1 installed. compiling with
CXX=clang++
CXXFLAGS= -stdlib=libc++ -std=c++11 -m64
(further see attachments)

I fear there is perhaps something fundamentally wrong with the (setup of) my compiler (although hard to believe as well). The program is very short (only 70 lines) and the make file only 2 lines. Anyone an idea?
Hope I don’t bother,
Cheers
Merijn

  • part of the output from valgrind:
    ==28059== Invalid read of size 4
    ==28059== at 0x100001DCC: main (PlotPlay_Minimum.cc:62)
    ==28059== Address 0x100020e74 is 0 bytes after a block of size 4 alloc’d
    ==28059== at 0x4D11: malloc (vg_replace_malloc.c:303)
    ==28059== by 0x47104: operator new(unsigned long) (in /usr/lib/libc++.1.dylib)
    ==28059== by 0x100001A3A: main (PlotPlay_Minimum.cc:47)
    ==28059==
    MinimalSegfaultDir.zip (57.8 KB)

Hi,

the correct way to allocate memory on the heap is described here:
cplusplus.com/reference/new/operator%20new[]

Hi,

Adding to Danilo’s reply, real quick (didn’t look at your code yet):
new float(binEdges.size())
allocates one float on the heap and initializes it with the value binEdges.size(). You probably want
new float[binEdges.size()] - allocate an array of floats?

Does that solve it?

Cheers, Axel.

Hi Axel,

That was exactly the line I was referring to. I think it does solve it.

Cheers,
D

Dear Axel and D, yes this solves it many thanks!

Honestly sorry for bothering with something that trivial, I thought with new the size was done with ()… Aside I got confused because:
-the compiler didn’t complain about the statement
-for some reason remotely it did run…
Again sorry, I just looked to deep into it.
Cheers
Merijn

Hey no problem. Good that you are not stuck anymore!