• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 663
  • Last Modified:

How to assign memory to static members of a class? - C++

I have a class with few static char* variables. How do I assign and free their memory? Please explain with sample code.
0
sukhoi35
Asked:
sukhoi35
  • 6
  • 6
  • 4
  • +4
4 Solutions
 
jkrCommented:
Declare them with the class and provide an instatiation in your immplementation, e.g.
class foo {

public:

  foo () { text = "test"; }

  // ...

protected:
  static char* text;
};

// ...

// this is where the static member is placed
char* foo::text;

Open in new window

0
 
Frosty555Commented:
You can do it exactly as you normally would with regular char* variables. Static variables operate identically to regular variables except you that you can only reference static variables from within static functions/methods.
0
 
jkrCommented:
BTW, if you meant how to assign dynamically allocated memory - that could be done like
class foo {

public:

  foo () { if (text == NULL) text = new char[42]; }

  // ...

protected:
  static char* text;
};

// ...

// this is where the static member is placed
char* foo::text = NULL;

Open in new window

0
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
phoffricCommented:
Here are links with examples showing how to use new, new[], delete, and delete[].

Just replace the example type with char.

// http://www.cplusplus.com/reference/std/new/operator%20new/

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20new[]/
// operator new[] example
#include <iostream>
#include <memory>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {
  // uses first version:
  int * p1 = new int[5];

  // uses second version:
  int * p2 = new (nothrow) int[4];

  // uses third version:
  pair <myclass*,ptrdiff_t> p3 = get_temporary_buffer<myclass>(3);
  new (p3.first) myclass[3];   // calls constructors
  return_temporary_buffer(p3.first);

  return 0;
}

// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20delete/

// operator delete example
#include <iostream>
#include <new>
using namespace std;

struct myclass {
  myclass() {cout <<"myclass constructed\n";}
  ~myclass() {cout <<"myclass destroyed\n";}
};

int main () {
  myclass * pt;

  pt = new myclass;
  delete pt;

  return 0;
}


// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20delete[]/

// operator delete[] example
#include <iostream>
#include <new>
using namespace std;

struct myclass {
  myclass() {cout <<"myclass constructed\n";}
  ~myclass() {cout <<"myclass destroyed\n";}
};

int main () {
  myclass * pt;

  pt = new myclass[3];
  delete[] pt;

  return 0;
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
If you are referring to the syntax required to initialise a static it's like this.
class my_static
{
   static char * str;
};

char * my_static::str = "hello world"; // doesn't need to be free'd

Open in new window

0
 
sukhoi35Author Commented:
Hi Experts,
Thanks for your responses. I actually need to dynamically allocate memory to a static char* in one of my methods. I would like to know how to release the memory at the end of the program i.e. before the application exits? I mean, where do I include the delete?
0
 
Subrat (C++ windows/Linux)Software EngineerCommented:
Inside  the destructor,

if (p!=NULL)
 delete[ ] p;           // if Allocating array of chars
0
 
Xper4netCommented:
The better solution I used in this case is to create also a static counter of object:

in header :
class MyObject
{
static int _count ;
static char* _text ;

public:
  MyObject() { _count++ ; if (text == null) _text = new char[10] ;  }
  ~MyObject { _count-- ; if (_count == 0) { delete[] _text ; _text=NULL;} }
} ;

in cpp file ;

MyObject::_count=0;
MyObject::_text = NULL ;
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> I would like to know how to release the memory at the end of the program i.e. before the application exits?

If it's static you don't actually need to as it will be released for you but, of course, this is a little unclean and can make some memory leak checkers unhappy. You can use atexit to register a function to do all your cleanup.

http://www.cplusplus.com/reference/clibrary/cstdlib/atexit/
0
 
Xper4netCommented:
atexit is not a good advice regarding OOP rules.
A class have to manage its own allocations, it must not depend on external actions. Otherwise it is not ready to be reused in another context.
0
 
sukhoi35Author Commented:
In case I am using the 'static char* charBuffer' in a fread operation, something like:

FILE *fpointer = fopen(filePath, "rb");
fread (charBuffer,1,fileLen,fpointer);

Do I need to worry about releasing the charBuffer memory here also?

Please clarify.
0
 
phoffricCommented:
If you have, for example:
    charBuffer = new char [fileLen+1];
Then when you are done processing charBuffer, you should release it.
0
 
phoffricCommented:
Here is a C example of fread and memory allocation and freeing using malloc and free (instead of new and delete).
     http://www.cplusplus.com/reference/clibrary/cstdio/fread/
/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;

Open in new window

0
 
Xper4netCommented:
If you use my solution, you wouldn't have to free allocated buffer after fread, as it will be done when last object of its class will be destroyed. Then you could use the same buffer for further read operations.
@phoffric : your comment is right, but not Object Oriented.
0
 
sukhoi35Author Commented:
Thanks
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> atexit is not a good advice regarding OOP rules.

The question is about releasing memory allocated to a static... at this point we are not even discussing OOP since statics are NOT instance objects and to presume they are and then allocate de-allocate in an instance constructor is a thread race condition waiting to happen. In other words, the very essence of what the asker is trying to do is probably flawed but using atexit to perform final clean-up is not itself an intrinsically bad idea -- although, as I pointed out, also not absolutely necessary since the OS will perform this anyway.

>> @phoffric : your comment is right, but not Object Oriented.

In all fairness a separate object is also not required either... one could just use a vector.
0
 
Xper4netCommented:
@evilrix : author start with "I have a class with few static char* variables".

So, it seems that we were talking about OOP. In OOP static members must be considered as class part and managed exclusively by the class. Otherwise, they've nothing to do inside it, and it's rather a design issue.

It's more than a reusability condition, it's a reliability question. Of course, developpers who manage software with several thousand lines of code can forget that without great pain. But when you deal with millions line of code, everything must be cleanly done, otherwise it never works fine. As well starting with the good rules.
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> So, it seems that we were talking about OOP.

static variables are not class instance variables... they belong to the class and not any specific instance. They are just variables with class scope. By their nature, static class members do not belong to any instance therefore they are not bound to the same OOP rules as instance variables. To imply otherwise is very misleading. Why do you think the syntax for initialising a static class member does not use any constructor? There is very little difference between a class static and a namespace level variable in terms of semantics and, to a large extent, syntax.

If you wish to debate this further we can, but not here... post in our expert thread and we (including the other experts) can discuss it further as you wish.

Thanks.
0
 
Xper4netCommented:
I absolutely not agree with your static member considerations...but I've lost exert thread link (and I couldn't retrieve it in my comment history ?). Can you share it again please?
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> Can you share it again please?

Of course.

http://www.experts-exchange.com/Q_26581726.html
0
 
Xper4netCommented:
Trying to post in this thread, I had the following message:
"You do not have the proper permissions to post a Comment in this Topic Area"
??
0
 
evilrixSenior Software Engineer (Avast)Commented:
There has been an issue with this weeks release that has caused a number of permissions problems - including breaking some users access to PDs. It will; hopefully, be resolved with this weeks release... normally pushed around Thursday.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 6
  • 4
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now