Hi,

Is this a valid while loop? :

while((grid[tr][tc]=='0'||grid[tr][tc]==s[i]) && tr<row && count<strlen(s))
       { ++count;
         ++tr;
       }

Although the full program compiles fine, but sometimes my program crashes during runtime giving me a "Access violation(Segmentation Fault)" error and the debugger points to this loop statement... By the way, I'm using dev c++ ...

Regards,

Dani AI

Generated

Nice fix by — the runtime crash was almost certainly caused by evaluating grid[tr][tc] before verifying tr is inside the array. In C/C++ the && operator short‑circuits left‑to‑right, so putting the bounds check first prevents an out‑of‑bounds access. That ordering change explains why the crash went away for .

Extra safe practices to avoid similar problems:

  • Precompute the string length once instead of calling strlen repeatedly; strlen returns an unsigned size_t, so use size_t for counters to avoid signed/unsigned issues.
  • Check every index you use (row and column bounds, and any index into s) and verify pointers (e.g., grid[tr] is not NULL) before dereferencing.
  • Watch for accidental use of the bitwise & or | instead of &&/|| — those do not short‑circuit and will evaluate both sides.
  • Add defensive assertions or explicit checks before the loop so the loop condition is not the only place that enforces invariants.

Example pattern (adapt to your types and column bounds):

size_t len = strlen(s);
size_t cnt = 0;

/* ensure tc < cols and grid rows are valid before loop */
while (tr < row && cnt < len && grid[tr] != NULL && tc < cols &&
       (grid[tr][tc] == '0' || grid[tr][tc] == s[i])) {
    ++cnt;
    ++tr;
}

Debugging tips: enable compiler warnings (-Wall -Wextra), run with AddressSanitizer (-fsanitize=address) or valgrind to catch invalid memory access, and use assertions or a debugger to inspect tr, tc, i, and pointer values at the crash site. These steps make it much easier to find the exact out‑of‑range access if it recurs.

Recommended Answers

All 3 Replies

I suggest to write it as

while((tr < row) && (grid[tr][tc]=='0'||grid[tr][tc]==s[i]) && (count<strlen(s)))
       { ++count;
         ++tr;
       }

If tr < row fails, grid[tr] will not be computed :)

WOW!! You suggestion worked!! My program no more crashes during runtime ! THANKS!

hehe !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.