473,834 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Different Variables Use Same Memory

I am using the Redhat version of Linux and GNU C++.

It is not clear to me whether this is a Linux issue or a C++ issue. I
do not have this problem running the same program on Windows but
tweaking the C++ code appears to fix the problem on Linux.

I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program uses
both classes. I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten. I found that the problem appears to go away when I change
thet declaration of the static array to public. However, I am not sure
I understand the issues involved. In fact, I am not really clear of
the advantages of declaring a variable as private as opposed to public,
apart from not wanting someone to modify the variable erroneously.
However, it appears that declaring it as private makes the program go
ahead and erroneously change it anyway.

I should also point out that the class where the static array is
declared privately, has the class with the publicaly declared structure
as one of its class objects. I have no idea why the compiled code
would make them use the same memory.

Any clarification of this/these issues would be greatly appreciated.

Thanks,
Peter.

Oct 31 '06 #1
18 2638
Ma**********@ex cite.com wrote:
I am using the Redhat version of Linux and GNU C++.

It is not clear to me whether this is a Linux issue or a C++ issue. I
do not have this problem running the same program on Windows but
tweaking the C++ code appears to fix the problem on Linux.

I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program uses
both classes. I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten. I found that the problem appears to go away when I change
thet declaration of the static array to public. However, I am not sure
I understand the issues involved. In fact, I am not really clear of
the advantages of declaring a variable as private as opposed to public,
apart from not wanting someone to modify the variable erroneously.
However, it appears that declaring it as private makes the program go
ahead and erroneously change it anyway.
The fact that the variable is private limits the places you have to look
when trying to figure out what you did wrong to cause the array writes
to stomp on the structure. That's a huge benefit in my book.
I should also point out that the class where the static array is
declared privately, has the class with the publicaly declared structure
as one of its class objects. I have no idea why the compiled code
would make them use the same memory.

Any clarification of this/these issues would be greatly appreciated.
They "use the same memory" because you are accessing one or both of them
incorrectly. It seems to go away because when you move one to the
"public" section of the class you are changing the order that they are
laid out in memory, thus you are overwriting some other part of memory
instead of the particular structure you noticed the problem in. What you
need to do is find out where you are jumping the bounds of your array
and fix that code.

One solution would be to replace the array with a vector and use the
"at" member-function or create some sort of checked array class that
alerts you when you write outside of it.

--
To send me email, put "sheltie" in the subject.
Oct 31 '06 #2
This almost has to be a compiler or environment problem
rather than a language or programming problem (unless
there is something you're not telling us).

Even so it might be useful to try to create the minimal
program that exhibits the problem and analyze that.

Steve
Oct 31 '06 #3

MajorSetb...@ex cite.com wrote:
I am using the Redhat version of Linux and GNU C++.

It is not clear to me whether this is a Linux issue or a C++ issue. I
do not have this problem running the same program on Windows but
tweaking the C++ code appears to fix the problem on Linux.

I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program uses
both classes. I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten. I found that the problem appears to go away when I change
thet declaration of the static array to public. However, I am not sure
I understand the issues involved. In fact, I am not really clear of
the advantages of declaring a variable as private as opposed to public,
apart from not wanting someone to modify the variable erroneously.
However, it appears that declaring it as private makes the program go
ahead and erroneously change it anyway.

I should also point out that the class where the static array is
declared privately, has the class with the publicaly declared structure
as one of its class objects. I have no idea why the compiled code
would make them use the same memory.

Any clarification of this/these issues would be greatly appreciated.

Thanks,
Peter.
How did you initialize the static array?
Why is the array static?
Why can't you provide minimal code?

#include <iostream>

class A
{
static int narray[10];
public:
static int get(int index) { return A::narray[index]; }
static void set(int index, int val) { narray[index] = val; }
};

int A::narray[] = { 0,1,2,3,4,5,6,7 ,8,9 }; // initialized array

int main()
{
A a;
a.set(5, 50);
for( size_t index = 0; index < 10; ++index)
{
std::cout << a.get(index) << std::endl;
}
return 0;
}

/*
0
1
2
3
4
50
6
7
8
9
*/

Oct 31 '06 #4
Hello,
Ma**********@ex cite.com wrote:
I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program
uses both classes.
I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten.
Any clarification of this/these issues would be greatly appreciated.
There is pretty surely a programming error in your code leading to
undefined behaviour. This could be due to overruns of some memory area,
it could be due to keeping some area in use after freeing or deleting.
These kinds of errors can be notoriously hard to identify. It is almost
impossible to create minimal examples to make it easy for others to
help, because minimal changes in the code might cause the crash going
away.

You have basically two options:

1. Do it the hard way, and nail it down: Learn about setting watchpoints
in gdb, or whatever your favourite debugger is. Make sure you have
deterministic failing runs of your code, i.e. all adresses and values
stay constant between different runs and then try to find out all
occasions, where the corrupt memory area has been in use before the
crash, and check, whether all parties play fair.

It looks like you have done some part of this already, you have found
the data structures with the conflict, now you have to find out which
one is first, and how the other one gets into the same area.

2. Use valgrind to find possible errors in using heap memory. It is
quite probable, that valgrind will identify your problem, but there is
no warrant.

Additionally you could write some procedures checking your data
structures, i.e. scanning them and touching the memory. Insert calls to
those checking procedures at viable places in your code. This can help
both basic options to get to the interesting places earlier.

Most probably you will have to know in detail, at least for the data
structures involved in the crash, where and when memory is allocted and
freed again, i.e. the full lifecycle.

Bernd Strieder

Oct 31 '06 #5
Ma**********@ex cite.com wrote:
I am using the Redhat version of Linux and GNU C++.

It is not clear to me whether this is a Linux issue or a C++ issue.
I bet it is neither Linux nor C++; most likely a programming error.
Are you an experienced C++ user, or are you a beginner?
I
do not have this problem running the same program on Windows but
tweaking the C++ code appears to fix the problem on Linux.
I spent several years working on the optimizer for C (and, implicitly, C++)
for the UNIX OS. People persisted in filing trouble reports on the optimizer
(which ran between the compiler and assembler steps in that system) because
their programs worked unoptimized (or so they said) and failed when optimized.

It turned out that the problems were in their source programs. They were
faulty. One thing to note about an optimizer is that _for correct programs_,
the optimized program should give the same results as the unoptimized ones.
And our optimizer did that. But it did not guarantee to give the same
results for incorrect programs.

One example is that for optimized programs, we did register allocation even
if the programmer did not explicitly declare a variable to go into a
register. And we overloaded registers. If a variable needed to be in a
register in one part of a function but not in the rest, and another variable
needed to be in a register in another part of a function, they could both be
assigned to the same register. Now consider what happens when the program
uses a variable, to which no value has been assigned, as a pointer. While
_not required_, a memory location is typically zero until a value is
assigned to it. Now in the case of overloaded registers, if a variable has
no value assigned to it, what the program gets is just whatever was in the
register, which is usually non-zero. So in the unoptimized case, the program
gets a null pointer (which should crash the program), where in the optimized
case, the program just uses some memory location somewhere.

This is a simple case of a programming error that runs differently on
different machines; different in this case being simply the unoptimized
machine and the optimized machine -- if you care to look at it that way.

Now in C++, the normal place to allocate memory is in the constructor
functions and the normal place to deallocate memory is in the destructor
functions. And I try to never let pointers to such memory escape from any of
the methods on an object. If you program like that, all your memory
allocations will be in the constructors and destructors, which should make
debugging easier: put tests in them to verify what is going on. And be sure
your constructors initialize everything.
>
I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program uses
both classes. I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten. I found that the problem appears to go away when I change
thet declaration of the static array to public. However, I am not sure
I understand the issues involved. In fact, I am not really clear of
the advantages of declaring a variable as private as opposed to public,
apart from not wanting someone to modify the variable erroneously.
However, it appears that declaring it as private makes the program go
ahead and erroneously change it anyway.
I normally have all variables in a class be private. Now I may have
functions in the class that return the value of a variable, but that is not
the same as making the variable public. Similarly, though less likely, I
might have a function that sets the value of a variable. But normally, that
is getting too fine: I might, in a reimplementatio n of the class, remove the
variable entirely. This should not affect the users of the class.
>
I should also point out that the class where the static array is
declared privately, has the class with the publicaly declared structure
as one of its class objects. I have no idea why the compiled code
would make them use the same memory.

Any clarification of this/these issues would be greatly appreciated.

Thanks,
Peter.

--
.~. Jean-David Beyer Registered Linux User 85642.
/V\ PGP-Key: 9A2FC99A Registered Machine 241939.
/( )\ Shrewsbury, New Jersey http://counter.li.org
^^-^^ 07:30:01 up 10 days, 9:57, 3 users, load average: 4.41, 3.78, 3.53
Oct 31 '06 #6
Jean-David Beyer wrote:
Ma**********@ex cite.com wrote:
>I am using the Redhat version of Linux and GNU C++.

It is not clear to me whether this is a Linux issue or a C++ issue.

I bet it is neither Linux nor C++; most likely a programming error.
Are you an experienced C++ user, or are you a beginner?
>I
do not have this problem running the same program on Windows but
tweaking the C++ code appears to fix the problem on Linux.

I spent several years working on the optimizer for C (and, implicitly, C++)
for the UNIX OS. People persisted in filing trouble reports on the optimizer
(which ran between the compiler and assembler steps in that system) because
their programs worked unoptimized (or so they said) and failed when optimized.

It turned out that the problems were in their source programs. They were
faulty. One thing to note about an optimizer is that _for correct programs_,
the optimized program should give the same results as the unoptimized ones.
And our optimizer did that. But it did not guarantee to give the same
results for incorrect programs.

One example is that for optimized programs, we did register allocation even
if the programmer did not explicitly declare a variable to go into a
register. And we overloaded registers. If a variable needed to be in a
register in one part of a function but not in the rest, and another variable
needed to be in a register in another part of a function, they could both be
assigned to the same register. Now consider what happens when the program
uses a variable, to which no value has been assigned, as a pointer. While
_not required_, a memory location is typically zero until a value is
assigned to it. Now in the case of overloaded registers, if a variable has
no value assigned to it, what the program gets is just whatever was in the
register, which is usually non-zero. So in the unoptimized case, the program
gets a null pointer (which should crash the program), where in the optimized
case, the program just uses some memory location somewhere.

This is a simple case of a programming error that runs differently on
different machines; different in this case being simply the unoptimized
machine and the optimized machine -- if you care to look at it that way.

Now in C++, the normal place to allocate memory is in the constructor
functions and the normal place to deallocate memory is in the destructor
functions. And I try to never let pointers to such memory escape from any of
the methods on an object. If you program like that, all your memory
allocations will be in the constructors and destructors, which should make
debugging easier: put tests in them to verify what is going on. And be sure
your constructors initialize everything.
>I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program uses
both classes. I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten. I found that the problem appears to go away when I change
thet declaration of the static array to public. However, I am not sure
I understand the issues involved. In fact, I am not really clear of
the advantages of declaring a variable as private as opposed to public,
apart from not wanting someone to modify the variable erroneously.
However, it appears that declaring it as private makes the program go
ahead and erroneously change it anyway.

I normally have all variables in a class be private. Now I may have
functions in the class that return the value of a variable, but that is not
the same as making the variable public. Similarly, though less likely, I
might have a function that sets the value of a variable. But normally, that
is getting too fine: I might, in a reimplementatio n of the class, remove the
variable entirely. This should not affect the users of the class.
>I should also point out that the class where the static array is
declared privately, has the class with the publicaly declared structure
as one of its class objects. I have no idea why the compiled code
would make them use the same memory.

Any clarification of this/these issues would be greatly appreciated.

Thanks,
Peter.

Yep seen all that sort of stuff.

Another good one is to overwrite memory that 'doesn't belong to you' -
like putting a string too long in a buffer of fixed size. If its a local
variable it will smash the sack and crash the machine, but if its a
global or static variable, there is no guarantee WHAT will get
overwritten. It mighty be memory thats never used for anything, it might
be memory that is utterly crucial for the program to work - -say an
array of pointers to functions.. call into those and its 'bye bye kansas'

C at least (I am not a C++ man) does not define the contents of
temporary variables, or the order in real memory and precise location of
static or temporary variables. I am not sure about 'malloc()'ed) memory
either.

Nothing is easier to declare a local pointer, and access memory it
points to without initialising it first.

{
char *p;
strcpy(p, "where will this end up");
}
Oct 31 '06 #7
The Natural Philosopher:
C at least (I am not a C++ man) does not define the contents of
temporary variables,

Yes it does. The following "temporary" has a well-defined value:

(int)53.5667

or the order in real memory and precise location of
static or temporary variables.

That's up to the implementation -- and it's irrelevant to the internal
workings of the program.

I am not sure about 'malloc()'ed) memory either.

Well you can store the address in a void*, and that's all you need to know.

Nothing is easier to declare a local pointer, and access memory it
points to without initialising it first.

{
char *p;
strcpy(p, "where will this end up");
}

That's not easy, not if you're very familiar with initialising pointers.
You could say that it's very easy to turn the kettle on without filling it
with water first. . . but what percentage of people don't check that
there's water?

--

Frederick Gotham
Oct 31 '06 #8

Bernd Strieder wrote:
Hello,
Ma**********@ex cite.com wrote:
I have a static array that is declared privately in one class and a
structure that is declared publicly in another class. The program
uses both classes.
I was getting core dumps and traced the problem down to
the fact that the array shares the same memory as the structure so
that, when an array element is written to, the structure is
overwritten.
Any clarification of this/these issues would be greatly appreciated.

There is pretty surely a programming error in your code leading to
undefined behaviour. This could be due to overruns of some memory area,
it could be due to keeping some area in use after freeing or deleting.
These kinds of errors can be notoriously hard to identify. It is almost
impossible to create minimal examples to make it easy for others to
help, because minimal changes in the code might cause the crash going
away.

You have basically two options:

1. Do it the hard way, and nail it down: Learn about setting watchpoints
in gdb, or whatever your favourite debugger is. Make sure you have
deterministic failing runs of your code, i.e. all adresses and values
stay constant between different runs and then try to find out all
occasions, where the corrupt memory area has been in use before the
crash, and check, whether all parties play fair.

It looks like you have done some part of this already, you have found
the data structures with the conflict, now you have to find out which
one is first, and how the other one gets into the same area.

2. Use valgrind to find possible errors in using heap memory. It is
quite probable, that valgrind will identify your problem, but there is
no warrant.

Additionally you could write some procedures checking your data
structures, i.e. scanning them and touching the memory. Insert calls to
those checking procedures at viable places in your code. This can help
both basic options to get to the interesting places earlier.

Most probably you will have to know in detail, at least for the data
structures involved in the crash, where and when memory is allocted and
freed again, i.e. the full lifecycle.

Bernd Strieder
Thanks very much for your help. I was not previously familiar with
valgrind and was very impressed. It is easy to use and found 30 memory
errors in my program. The error report was easy to understand and it
enabled me to fix the errors with little difficulty. Unfortunately,
the problem had not manifested itself after I reprivatised the static
arrays (by undoing the publicising changes). However, I could
certainly see the errors in the code after valgrind drew my attention
to them.

Thanks again,
Peter.

Oct 31 '06 #9

Salt_Peter wrote:
>
How did you initialize the static array?
Why is the array static?
Maybe I'm not using the correct term. I am declaring the array as
float faArray[64];
rather than
float *fpArray;
with a subsequent call to malloc() (or whatever).
Why can't you provide minimal code?
The code involved in the program is huge. I was not clear where the
problem was occurring although it did appear to be early in the
program. hence I asked the question in general terms. Valgrind found
about 30 memory errors and they may have been the cause. If not, I
will post the code where the problem appears to be occurring.

Thanks,
Peter.

Oct 31 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

137
7213
by: Philippe C. Martin | last post by:
I apologize in advance for launching this post but I might get enlightment somehow (PS: I am _very_ agnostic ;-). - 1) I do not consider my intelligence/education above average - 2) I am very pragmatic - 3) I usually move forward when I get the gut feeling I am correct - 4) Most likely because of 1), I usually do not manage to fully explain 3) when it comes true. - 5) I have developed for many years (>18) in many different environments,...
2
4206
by: Paul M | last post by:
Hi, This is on an AS/400 which can be a little strange but I think the basic question is portable. I have a (non-C) program that needs to make series of calls to some C programs/functions. The problem is that I need to initialise certain variables within the first C program called and then use them in subsequent calls to other C functions.
7
1264
by: James A | last post by:
Hi, I'm having trouble geting my head around this, although I know it's a pretty basic question. I have an application whereby an area of RAM is mapped to an array: unsigned char NV; Two consequtive elements are used to hold an unsigned int (2 bytes on this
27
2825
by: Madhav | last post by:
Hi all, I did not understand why do the global vars are initialized to NULL where as the block level variables have random values? I know that the C standard requires this as was mentioned in a recent thread. I want to know why this descrimination is in place. Can't all the variables be initialised to NULL automatically by the compiler? This would make programming a little easier.
17
5110
by: romixnews | last post by:
Hi, I'm facing the problem of analyzing a memory allocation dynamic and object creation dynamics of a very big C++ application with a goal of optimizing its performance and eventually also identifying memory leaks. The application in question is the Mozilla Web Browser. I also have had similar tasks before in the compiler construction area. And it is easy to come up with many more examples, where such kind of statistics can be very...
10
1820
by: ypjofficial | last post by:
Hello All, since the programs' stack is shared among all the function inside the program, I was just doing some R&D to see whether the same stack space is used for the variables inside the different functions are not. below is my code //program start void fun1() {int i;
15
3542
by: Juha Nieminen | last post by:
I'm sure this is not a new idea, but I have never heard about it before. I'm wondering if this could work: Assume that you have a common base class and a bunch of classes derived from it, and you want to make a deque which can contain any objects of any of those types. Normally what you would have to do is to make a deque or vector of pointers of the base class type and then allocate each object dynamically with 'new' and store the...
1
29403
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
6
1946
by: Avi | last post by:
I need to implement the following calculation: f = (a*b) + (c*d) where a,b,c,d are given double values and f is a double variable for the result I found out that using two different implementations gives two different results: 1) In the first implementation I compute the entire equation in memory 2) In the second implementation I store intermediate to variables, and then load them to compute the final result.
0
9800
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10516
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9339
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7762
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5800
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4429
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3987
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3085
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.