ma************@gmail.com wrote:
>Check out these tools: valgrind or electric-fence.
I didn't check your source, but I guess you haven't used any assert()
checks, those are very useful to track down memory faults.
--
Tor <bwz...@wvtqvm.vw | tr i-za-h a-z>
Thanks for that, I will read the manual of those programs.
I don't understand why assert is supposed to be used. man assert is
not
so helpful. Can you give me an example of use of assert for tracking
memory faults?
In my code, I put systematically the following
if ((TheReg = (int*)malloc(nbVert*sizeof(int))) == 0)
Writing it this way:
if (NULL == (TheReg = malloc(nbVert*sizeof(*TheReg))))
is less error prone.
exit (EXIT_FAILURE);
Here is a function, not too trivial and not too difficult, and it
demonstrate usage of assert(). I left in the doxygen comments.
The idea of this function, was to pick fixed sized fields, from a buffer
like this:
char array[] = "1234567890ADDRESS-FIELD-1 ADDRESS-FIELD-2 ";
Hence, a call like
char s[40];
size_t n;
n = str_acpy(s, sizeof s, array+10, 20);
should copy "ADDRESS-FIELD-1 " into object 's' without overflow.
/**
* \fn size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
*
* \brief str_acpy() copy array of chars 'a', into a string 's'.
* 1. always null terminate output buffer 's'
* 2. never overflow output buffer 's'
* 3. truncatination is an error.
* \param s - target buffer
* \param max_s - size of target buffer
* \param a - array of chars
* \param alen - max lenght of input array
*
* \return strlen(s)
* (size_t)-1 on input errors,
* (size_t)-2 on truncate error
*/
size_t str_acpy(char *s, size_t max_s, const char *a, size_t alen)
{
size_t i,
rc = 0;
char *dst = s;
const char *src = a;
int has_been_null_terminated = 0;
/* pre-condition */
assert(s != NULL);
assert(a != NULL);
assert(max_s 1); /* require '\0' to be written */
assert(alen 0); /* require input to have data */
assert(alen < max_s); /* overflow check */
/* run-time checks - Remark 'max_s <= alen' is omitted */
if (s == NULL || max_s < 1 || a == NULL || alen < 1)
{
rc = (size_t)-1;
}
else
{
/* do copy */
for (i=0; i<max_s && i<alen; i++)
{
if (*src == '\0')
has_been_null_terminated = 1;
*dst++ = *src++;
if (has_been_null_terminated)
break;
rc++;
}
/* always null terminate destination string,
set error on trunc*/
if ( !has_been_null_terminated)
{
if (alen < max_s)
{
s[alen] = '\0';
}
else
{
s[max_s - 1] = '\0';
rc = (size_t)-2;
}
}
}
/* post-condition */
assert(rc < max_s);
assert(rc <= alen);
return rc;
}
--
Tor <bw****@wvtqvm.vw | tr i-za-h a-z>