?
Solved

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

Posted on 2010-11-09
23
Medium Priority
?
660 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 4
  • +4
23 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 34096349
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
ID: 34096351
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 200 total points
ID: 34096366
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 32

Expert Comment

by:phoffric
ID: 34096394
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 40

Expert Comment

by:evilrix
ID: 34097085
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
ID: 34099378
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 9

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 34099856
Inside  the destructor,

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

Accepted Solution

by:
Xper4net earned 1000 total points
ID: 34100011
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 400 total points
ID: 34100741
>> 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
ID: 34100764
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
 

Author Comment

by:sukhoi35
ID: 34100912
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
ID: 34100927
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 400 total points
ID: 34100933
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
ID: 34101556
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
ID: 34109838
Thanks
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34109860
>> 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
ID: 34110295
@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
ID: 34110344
>> 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
ID: 34119374
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
ID: 34123498
>> Can you share it again please?

Of course.

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

Expert Comment

by:Xper4net
ID: 34134944
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
ID: 34134955
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

Stack Overflow Podcast - Developer Story

Welcome to the Stack Overflow podcast recorded Thursday July 20 at Stack Overflow Headquearters in NYC. Your hosts today are podcast regulars Jay Hanlon, David Fullerton, and Ilana Yitzhaki, plus the quite irregular Matt Sherman (Stack Overflow Engineering Manager extraordinaire)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

770 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