Expert C Programming

(Jeff_L) #1

struck by the fact that they could easily have coded around the bug if they had invested a
small amount of time in investigating exactly what caused it. The moral of this story is two-
fold:



  1. Report to customer support all the product defects that you find. We can only
    fix the bugs that we know about and can reproduce (another source of
    frustration for us is government agencies who report problems but "for
    security reasons" will not provide even sanitized versions of the code that
    reproduces them).

  2. Zen and the art of software maintenance suggests that you should spend a
    little time investigating any bugs you find; there may be an easy
    workaround.


What we really want is the ability to grow a table as needed, so the only limit is the overall amount of
memory. And this is indeed possible if you don't declare your arrays directly, but instead allocate them
at runtime on the heap. There is a library call, realloc(), that reallocates an existing block of
memory to a different (usually larger) size, preserving its contents while doing this. Whenever you
want to add an entry to your dynamic table, the operation becomes:



  1. Check whether the table is already full.

  2. If it is, realloc the table to a larger size. Check that the reallocation succeeded.

  3. Add the entry.


In C code, this looks like:


int current_element=0;


int total_element=128;


char *dynamic = malloc(total_element);


void add_element(char c) {


if (current_element==total_element-1) {


total_element*=2;


dynamic = (char *) realloc(dynamic, total_element);


if (dynamic==NULL) error("Couldn't expand the table");


}


current_element++;


dynamic[current_element] = c;


}


In practice, don't assign the return value from realloc() directly to the character pointer; if the
reallocation fails, it will nullify the pointer, and you'll lose the reference to the existing table!


Programming Challenge

Free download pdf