Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

is or (¦¦) evaluation behavior guaranteed under ANSI? 2

Status
Not open for further replies.

dementg

Programmer
May 9, 2002
67
US
The following is a simplified example of something I'm trying to do. My question is whether the if() statement at the bottom is technically safe from causing a segfault crash:

Code:
typedef struct
{
  HWND hWnd;
  /* other elements... */
} GTWindow_t;

GTWindow_t **gtWindow=NULL;  /*pointer to an array of pointers to GTWindow_t*/

main()
{
  /* allocate 5 elements in gtWindow[] */
  gtWindow=(GTWindow_t **) malloc(sizeof(GTWindow_t *) * 5);
  /* initialize gtWindow[0..4] to NULL */
  /* bunch of code... */

  if (gtWindow[1]==NULL) || ((gtWindow[1]->hWnd)!= desiredValue)
  {
    printf("either gtWindow[1] doesn't point to anything or what it points to isn't what we want");
  }
}


If I try to look up gtWindow[1]->hWnd, but gtWindow[1] is NULL, then that would be an invalid memory reference and we'd get a segmentation fault.
But on any decent compiler, if the first condition of an OR comparison is true then it won't try the second condition. Is that behavior guaranteed under ANSI? Would the above code be crash-prone depending on the compiler? I could redesign the if() to avoid this issue, but it would make it slightly less efficient and regardless I'm curious whether the OR behavior is guaranteed. Thanks.
 
Yes, the behaviours of && and || are guaranteed to stop as soon as the end result is known.

My other suggestion would make sure gtWindow itself is non-NULL just after the malloc call.


> gtWindow=(GTWindow_t **) malloc(sizeof(GTWindow_t *) * 5);
In ANSI-C, the cast is not necessary, since if you've included stdlib.h, the cast from void* to type* is automatic.
The downside is that if you don't include stdlib.h, it (the cast) will mask this, and you could lose out in the implicit int-to-pointer conversion which will result from it.

Also, the cast is necessary if you're actually compiling this code as C++, but you should be using 'new' in this case.

> main()
Whilst this implies 'int main()' in the current version of ANSI-C, the new C99 version of the standard no longer allows functions to have implicit return types.

--
 
Thanks for the info. The other issues you mentioned aren't present in the original code, except I do have the cast you discussed. I'm kind of non-committed about C++, I tend to write C style code in .cpp files, sometimes using a few C++ features. I'll look into the "new" statement, I'm actually not familiar with it. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top