I have a question regarding scope for a character array defined as follows:

saveDataObj->save("This is the first entry", 1, 2);

Here is how the SaveData class has been defined:

class SaveData {

  struct entry{
     const char* data;
     int data1;

  entry* mpData;
  static int iter;

   //allocates space for 100
   mpData = new entry[100];

//saves the passed in data
SaveData::save(const char* pData, int intData1)
   mpData[iter].data = pData;
   mpData[iter].data1 = intData1;


   for (int i=0; i < 100; i++)
       cout << "data:" << mpData[i].data << endl;


//I have another class which saves the data by calling save()

  SaveDataObj->save("This is the first entry", 1, 2);

  SaveDataObj->save("This is the second entry", 1, 2);

I'll be saving upto 100 different character arrays.

My question is:

1) Will the character array "This is the first entry" be considered as
local to the function TestClass:save(). Which means this array
will be saved on the stack and will be deleted from the stack
once I exit the function?

2) Is this equivalent to defining a local char pointer as follows:

      const char* pData = "This is the first entry";
      SaveDataObj->save(pData, 1, 2);

3) In SaveData::save()

SaveData::save(const char* pData, int intData1)
      mpData[i].data = pData; 
      mpData[i].data1 = intData1;

mpData.data points to passed in pData.

What will happen if I later call print() to dump all the saved data?
Will I able to dump my saved data or will I be dumping garbage?

Please let me know.

(I'm new to this forum and this is my first post.)

Thanks in advance.

Edited by cthreash: n/a

7 Years
Discussion Span
Last Post by cthreash

1) No, the lifetime of a string literal is equal to that of the program.
2) Yes, the address you're saving is still that of the string literal.
3) You're pointing to a string literal, so it's all good.

However, note that identical string literals may share memory, so you could have two SaveData objects that point to the same address. If you treat the objects as if the addresses are unique, you may encounter problems.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.