0

I have a function that is supposed to return a double pointer, it is supposed to return the address of the pointer to a piece of data which in this example is a character array

The original data is sent as a parameter in the constructor

Classname::Classname(void* fdata);

It is then copied to a void* data member called frame_data with

frame_data = fdata;

The function that returns the double pointer is defined as

void** Classname::data(){
    return &frame_data;
}

Finally, the function that later calls data()

std::sprintf(*(char**)classn.data(), "LOOP No: %d", loop);

And this is where the program segfaults. Obviously something is wrong, but I'm just not sure where the problem comes in. In this program the sprintf line isn't changeable, as is the fact that data() returns a double pointer, any idea where I'm going wrong?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Sizdian
  • 79
  • 1
  • 2
  • 9
  • 1
    where do you allocate the string buffer memory? – Bathsheba Dec 06 '13 at 20:16
  • Avoid passing pointers - having references you will see where the error is. –  Dec 06 '13 at 20:17
  • 3
    this is precisely why everyone stopped using void* – Oakdale Dec 06 '13 at 20:24
  • @Dieter Lücking as far as I know, I have to pass a pointer, unless I just have the terminology messed up – Sizdian Dec 06 '13 at 20:24
  • Underneath the hood (correct me if I'm wrong) a pointer and a reference are stored the same way and allow for the reference of an object to be modified instead of a copy. The reason references are preferred is that references in C++ are immutable and must be initialized on creation. A pointer, on the other hand, may point to any piece of memory at any time (including 0 or null). You can cause a reference to point to bad data by accident, but in practice and with good programming techniques, it's a lot harder. – David Peterson Dec 06 '13 at 20:53
  • 1
    There is nothing wrong in the code you are showing us, the problem is somewhere else. You should prepare an [SSCCE](http://sscce.org/). – Casey Dec 06 '13 at 21:01

0 Answers0