tags:

views:

69

answers:

2

When a user moves the slider it will trigger a signal and based on that I want to call a method readData from dataClass, to return me a string and then print it in guiClass. But it does not work. I get Program received signal: “EXC_BAD_ACCESS”. I am using Xcode. As soon as I move the slider the program crashes and highlights line 9.

 1  //---guiClass---
 2  guiClass::guiClass(QWidget *parent) : QWidget(parent)
 3  {
 4      connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(slider_Moved(int)));
 5  }
 6  void guiClass::slider_Moved(int val)
 7  {
 8      //Don't worry about val for now.
 9      cout << dataClassPtr->readData(val) << endl;
10  }

    //---dataClass---
    char* dataClass::readData(int lines) {
       char *str = "hello world";
       return str;
    }
A: 

The pointer str in dataClass::readData is allocated on the stack. You can't use it once the function has returned.

Try something like:

QString* dataClass::readData(int lines) 
{
    return new QString("hello world"); 
}

Don't forget to delete the QString when you are finished with it

PiedPiper
so if i allocate memory for str using calloc and then return a pointer to that? will that work?
rashid
That should do it. Or create a QString with new()
PiedPiper
I tried the following:char* dataClass::readData(int lines) char *memData = (char *)calloc(30, sizeof(char)); char *data = "hello world"; sprintf(memData, "%s", data); return memData;}but no luck!!! what am i doing wrong??
rashid
You don't need calloc for the string data, you need it for the pointer to the string.
PiedPiper
char \*str = "hello world"; shouldn't even compile (or should give you a warning about being deprecated). "hello world" is const, so it should be char const\* str.
Intransigent Parsnip
+1  A: 
  1. Use a debugger (if you don't know how, learn :-)
  2. Verify that dataClassPtr points to a valid instance of dataClass
  3. char *str = "hello world" is wrong (string literals are const; should be const char* str)
  4. Why not have readData return a QString instead?
Intransigent Parsnip