Solved

to know is pointer pointing to valid object

Posted on 2001-09-18
24
308 Views
Last Modified: 2013-11-20
Hello all,
I have array of pointers on my objects
ex
myobj *array[100];

now i dinamicly create objects during runtime.
How can I verify is the object ex. array[0] valid myobj ?

I have dont this by catching exceptions when trying to access object but it works only in debug mode in release it dont work at all

0
Comment
Question by:monster2
  • 7
  • 7
  • 4
  • +3
24 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 6490459
If you use:

myobj *array[100];

you have no way of knowing since this statement does not provide anything except a SPACE to store 100 pointers.

A common technique is to fill such an array with NULL so that you then know that an item in the array is valid or NULL.

for(int i=0; i<100; i++)
  array[i] = NULL;

Then, as you use these in your app, be sure to store NULL back into the pointer as you free or delete any item pointed to by the element.
0
 

Author Comment

by:monster2
ID: 6490546
O.K.

:)
0
 
LVL 30

Expert Comment

by:Zoppo
ID: 6491127
Wouldn't it be easier to initialize the array by
myobj *array[100] = {0};
0
 
LVL 32

Expert Comment

by:jhance
ID: 6491165
Maybe....

I'm usually don't think about initializers since I spent so many years programming C on embedded systems that didn't support them.

But, as always, there are probably 10 ways to accomplish this.
0
 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6491516
Let's say you have a pointer to an object CObj* p that contains a data of type pointer void* m_pData

If u use AfxIsValidAddres( p->m_pData ) returns false if adress is not valid.
0
 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6491581
Hello vetzeloo
0
 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6491612
You can use smart pointer.

A smart pointer it's a class let's say CSmartPtr that contains a pointer let's say m_pObj.
To make one override the -> operator to return the *pObj value and then you can access directly the methods and data in the pointer like in the example below:

CSmartPtr ptr;

ptr->fnc();

where fnc is a member function of m_pObj.


 You can implement exceptions to test if pObj is valid or you can make a function to check. To make a more efficient implementation I sugest you to take a look at the CSting class source code witch incapsulates a LPTSTR var. You can find some useful ideeas there.
0
 

Expert Comment

by:AdrianBogdan
ID: 6491641
4 Zoppo: I didn't quite get your point: your code "says" array[0] = 0 and for the rest of the array God save us.. :)

4 monster2: When you have a pointer it is best (the best!!!) to be SURE that its value is ALWAYS NULL when it is uninitialized (points to an unallocated mem. zone). So this solves also your case.
Otherwise, consider Java.. :P

I could give you some convincing examples but would I took them from "Effective C++" and "More Effective C++", which wouldn't be fair :)

So, I recomand 2 you all to read those books. A university-mate has them on his page:
- http://lci.cs.ubbcluj.ro/~raduking/Books/Effective/EC/INDEX.HTM

- http://lci.cs.ubbcluj.ro/~raduking/Books/Effective/MEC/INDEX.HTM

wish you pointer-safe coding,

Adi
0
 

Expert Comment

by:AdrianBogdan
ID: 6491646
hi 2 u 2, boule! :))
0
 

Author Comment

by:monster2
ID: 6491908
:)) processing ........ (Will take a while)
0
 
LVL 3

Expert Comment

by:GlennDean
ID: 6492388
IF you're object inherits CObject and it has runtime type info for the object, then you can use IsKindOf function to check if any element is one of your objects
0
 
LVL 30

Expert Comment

by:Zoppo
ID: 6492713
to Adrian: believe me or not (coz I couldn't find some C specs for this), but it works ...
initializing static C arrays with = {0}; initializes all elements of that array to 0.

greetings,

Roman
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6492751
Actualy the compiler takes care of filling the array with 0 when you declare it. Try int *a[100] and then look at the value of a elements. If you make int *a[100] = {1} only the first elem has the value of 1, the rest ar 0.
0
 
LVL 30

Expert Comment

by:Zoppo
ID: 6492783
hmm, if you only declare i.e.
int x[10];
then the elements of x aren't initialized at all, but declaring it as
int x[10] = {0};
initializes all elements to 0.
0
 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6492907
Here is a little listing that expalains what happens. :)

25:       int a[10];
26:       int b[10] = { 0 };
//Here assigns 0 to b[0]
004014CD   mov         dword ptr [ebp-60h],0
//Here fils the rest with 0. ???
004014D4   mov         ecx,9
004014D9   xor         eax,eax
004014DB   lea         edi,[ebp-5Ch]
004014DE   rep stos    dword ptr [edi]
27:       int c[10] = { 1 };
//Here assigns 1 to c[0]
004014E0   mov         dword ptr [ebp-88h],1
//Here fils the rest with 0. ???
004014EA   mov         ecx,9
004014EF   xor         eax,eax
004014F1   lea         edi,[ebp-84h]
004014F7   rep stos    dword ptr [edi]
28:       a[0] = 55;
004014F9   mov         dword ptr [ebp-38h],37h

I don't see why does that ? Anybody knows ?
0
 
LVL 2

Expert Comment

by:BogdyPtr
ID: 6492910
Here is a little listing that expalains what happens. :)

25:       int a[10];
26:       int b[10] = { 0 };
//Here assigns 0 to b[0]
004014CD   mov         dword ptr [ebp-60h],0
//Here fils the rest with 0. ???
004014D4   mov         ecx,9
004014D9   xor         eax,eax
004014DB   lea         edi,[ebp-5Ch]
004014DE   rep stos    dword ptr [edi]
27:       int c[10] = { 1 };
//Here assigns 1 to c[0]
004014E0   mov         dword ptr [ebp-88h],1
//Here fils the rest with 0. ???
004014EA   mov         ecx,9
004014EF   xor         eax,eax
004014F1   lea         edi,[ebp-84h]
004014F7   rep stos    dword ptr [edi]
28:       a[0] = 55;
004014F9   mov         dword ptr [ebp-38h],37h

I don't see why does that ? Anybody knows ?
0
 

Expert Comment

by:AdrianBogdan
ID: 6492952
** 4 monster2:
about the processing you're right, there's always a compromise; this time is between safe coding and speed. How large is your array? How many times during your app's run do you initialized it? If is just once and your array is not "that" large... but again "that" large could mean one or the other

** 4 GlenDean:
good idea, if you're using MFC's Run-time Class information

** 4 Zoppo (hi, Roman):
Must admit that I don't really know what C/C++ specs say about this, but I suppose that a compiler can not garantee for your vars being initialized. Although M$'s and Borland's (Inprise) compilers seem to do that. BTW, C++'s specs are available 4 download, but the PDF costs 18$; they f&*%ing !@#&#&^&
:))

I've made some testings before I post that. But seems like had to extend my tests.. :))
(I'm using MS VC++ SP 5)
Here's what I did 1st:

#include <iostream>

int* array[10];// = {0, (int*)1, (int*)2};

void output()
{
     for (int i = 0; i < 10; i++)
          std::cout << array[i] << " ";

     std::cout << std::endl;
}

void main()
{
     output();
}

And the alway's pointers were always initiliazed with NULL (debug & release configuration). So, without " = {0};" the array is initialiazed with NULLs.
if the initialization is:
int* array[10] = {(int*)1};
doesn't mean that the array is filled with the value 1...
But the array was global...

So I declared it in main():
#include <iostream>

void output(int** array)
{
     for (int i = 0; i < 10; i++)
          std::cout << array[i] << " ";

     std::cout << std::endl;
}

void main()
{
     int* array[10];
     
     output(array);
}

The output is:
CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC
 CCCCCCCC

Which in the DEBUG config. the default value of the Microsoft's NO MAN'S LAND. Value used for tests for memory zones overflows. Which is very Microsoft specific.

same code's output in release config is:
002F07C8 0041506C 004064F2 004012D0 00405F67 004012D0 00408529 00132580 00408457
 00415000

As it should be, pretty random.. :)

From this point the test is continued by BogdyPtr (in the above code).
Looking at the disasm code. Seems like the M$ way is.
If the first k (where 1 <= k <= ARRAY's SIZE) values form an array are initialiazed on the declaration line, then cl.exe generates code to fill the rest of the array with NULL.

Anyone knows about what C++ specs say?


Anyway, I'm still saying that having pointer which are not set to NULL, when they don't point to any valid memory area can give you some real debugging nightmares..


wish you all happy coding,

Adi
0
 

Author Comment

by:monster2
ID: 6494640
looks  I pooked on VERY intereting topic :))
0
 

Author Comment

by:monster2
ID: 6494641
(looks like)
0
 

Expert Comment

by:AdrianBogdan
ID: 6495802
Indead it is:))
But I think there has been said all that could be said.
And you really have a few choises to solve your case.
0
 

Author Comment

by:monster2
ID: 6496292
the thing is that i hvae array of pointer to CWinThread objects.

now these object are calling AfxExitThread(0) to terminate existance.
I dont know when this call could occur so I need to know for sure is pointer pointing to VALID object or some memory never never land.

In debug I can use try catch but in realease this is not working properly .

so the question is how ca I know is pointer pointing to VALID CWinThread Object ?

P.S.
I should formulate question in this manner.
So excuse me if u can If not I will accept one of the current answers since I'm asking a slightly different toppic.
0
 
LVL 2

Accepted Solution

by:
BogdyPtr earned 50 total points
ID: 6496320
CWinThread class has a member var m_bAutoDelete witch says that the CWinThread object sould delete it's self when the thread execution endes. This var can be set via AfxBeginThread function or by accessing it using a var of CWinThread type. If set to false the object will not delete d so you can access the pointer in a safe way.

Next time give more details :).
0
 

Author Comment

by:monster2
ID: 6496437
time to close this topic
Thank You all
I can't slpit points :(
0
 

Author Comment

by:monster2
ID: 6496439
time to close this topic
Thank You all
I can't split points :(
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Rewrite URL With Encoded Characters 6 64
iSeries FTP Exit Program 8 114
Separate into files by filename 12 67
fix34  challenge 9 97
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

762 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

22 Experts available now in Live!

Get 1:1 Help Now