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:
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.
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.