PREV INDEX NEXT

Author: Stan Eisenstat
Subject: Common bugs
Date: Thursday, 27 Feb 2020, 14:04:51


1. strwrs times out on Test #12.

   Likely cause: The run-time of a loop like

       char copy[strlen(line)];
       for (int i = 0; i < strlen(line); i++)
	   copy[i] = line[i];
      
   depends quadratically on strlen(line) since there are
   strlen(line) iterations and the time to compute the
   stopping criterion on each iteration depends linearly
   on strlen(line).

   Fix:  Compute the value of strlen(line) outside the
   loop.

2. valgrind reports an invalid read or write in a block
   that was previously freed by realloc() during a call
   to another function.

   Likely cause: main() passes a char* line to a function
   such as the following:

     void foo (char *bar) {
	 bar = realloc (bar, 2 * strlen(bar) + 1);
	 return;
     }

   and realloc() allocates a new block of storage,
   assigning the address to the argument bar.  When
   foo() returns, line is still pointing to the old
   block.

   Fix:  Pass &line to foo() and change all references
   of bar to *bar (but be aware that the predence of *
   is lower than that of [] so that *bar[i] is the same
   as *(bar[i]), not (*bar)[i] as you might expect).

3. valgrind reports "Conditional jump or move depends on
   uninitialised value(s)" on a call to strlen().

   Likely cause: The string is not null-terminated.

   Fix:  Add the null character (but make sure that you
   allocated space for it).

--Stan-
PREV INDEX NEXT