Solved

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

Posted on 2010-11-09
23
653 Views
Last Modified: 2012-05-10
I have a class with few static char* variables. How do I assign and free their memory? Please explain with sample code.
0
Comment
Question by:sukhoi35
  • 6
  • 6
  • 4
  • +4
23 Comments
 
LVL 86

Expert Comment

by:jkr
Comment Utility
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
 
LVL 31

Expert Comment

by:Frosty555
Comment Utility
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
 
LVL 86

Assisted Solution

by:jkr
jkr earned 50 total points
Comment Utility
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
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
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
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
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
 

Author Comment

by:sukhoi35
Comment Utility
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
 
LVL 8

Expert Comment

by:Subrat (C++ windows/Linux)
Comment Utility
Inside  the destructor,

if (p!=NULL)
 delete[ ] p;           // if Allocating array of chars
0
 
LVL 5

Accepted Solution

by:
Xper4net earned 250 total points
Comment Utility
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
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 100 total points
Comment Utility
>> 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
 
LVL 5

Expert Comment

by:Xper4net
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:sukhoi35
Comment Utility
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
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
If you have, for example:
    charBuffer = new char [fileLen+1];
Then when you are done processing charBuffer, you should release it.
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 100 total points
Comment Utility
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
 
LVL 5

Expert Comment

by:Xper4net
Comment Utility
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
 

Author Closing Comment

by:sukhoi35
Comment Utility
Thanks
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> 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
 
LVL 5

Expert Comment

by:Xper4net
Comment Utility
@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
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> 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
 
LVL 5

Expert Comment

by:Xper4net
Comment Utility
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
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> Can you share it again please?

Of course.

http://www.experts-exchange.com/Q_26581726.html
0
 
LVL 5

Expert Comment

by:Xper4net
Comment Utility
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
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now