Setting pointer to null!
- From: Robby <Robby@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 31 Mar 2009 23:04:02 -0700
Hello,
As a rule of thumb, is it okay to declare a local pointer in a function and
set it to null right away like this:
====================
void f1()
{
int a, *x = NULL;
x = &a;
...... do other stuff....
}
====================
Or is it better like this:
===================
void f2()
{
int a, *x;
x = &a;
...... do other stuff....
}
=====================
The thing is that in F1, when we leave the function, x won't exist anymore,
so I don't see the need to set it to null in the first place. I could be
wrong in this assumption though!
Also in another sample code I was returning a pointer that could sometimes
not be assigned an address... this crashed my app. I guess I was returning a
null pointer in that instance.
For example, suppose I do this:
====================
typedef struct g{
int u;
} GSO;
GSO d[1];
GSO *f1(int w, GSO d[])
{
GSO *x = NULL;
if(w>10)
{ x= &d[0]; }
//..... do other stuff....
return x;
}
int main()
{
GSO *k=NULL;
int w = 5;
k = f1(w, d); // If my pointer returned is null.. what happens to k?
//.... other code...
return 0;
}
==================
If, w equals to 5, then the pointer is really not assigned an address and I
was returning it to the calling routine and that's what probably crashed the
app. Obviously I should of done something like this:
==============
if(w>10)
{ x= &d[0];
return x;
}
==============
In anycase, what is the rule of thumb, should we or should we not declare a
local pointer with null? To solve the afforsaid problem I simply took the
null out and there was no more crashes. But am I wrong in doing this?
Sorry for the oversimplified question, its just that I ran into this
particularity today and would like to know if anyone can help clear up this
issue.
Thanks for you feedback!
--
Best regards
Roberto
.
- Follow-Ups:
- Re: Setting pointer to null!
- From: Barry Schwarz
- Re: Setting pointer to null!
- From: Ulrich Eckhardt
- Re: Setting pointer to null!
- From: David Lowndes
- Re: Setting pointer to null!
- Prev by Date: Re: Handling Crashes in C++ program internally
- Next by Date: Re: Setting pointer to null!
- Previous by thread: Re: Handling Crashes in C++ program internally
- Next by thread: Re: Setting pointer to null!
- Index(es):
Relevant Pages
|