c++ - Strange behavior after memcpy with G++ -O2 -


edit: answered in comments

i forgot memcpy null pointer ub, if size argument 0. have relied on working long time.

the obvious solution seems add if before calling memcpy, had unacceptable overhead in @ least 1 case in past. need investigate more.

sorry, nothing more answer here.

(end edit)

#include <iostream> #include <algorithm> #include <string.h>  class dynarray {     double * data = nullptr;     size_t size = 0;  public:     void push_back(double val)     {         auto const newdata = new double[size + 1];          newdata[size] = val;          memcpy(newdata, data, sizeof(double) * size);          if (data)             std::cout << "non-null pointer: " << data << std::endl;          data = newdata;         ++size;     } };  int main() {     dynarray a;     a.push_back(0.5);     a.push_back(1.5); } 

http://coliru.stacked-crooked.com/a/3bf77603e7593b76

example output:

non-null pointer: 0 non-null pointer: 0x619c20 

it should clear data equals nullptr first call, if-check should skip printing. yet see "non-null pointer: 0" optimization (-o2).

if switch std::copy, works expected.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -