Statalist The Stata Listserver

[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: How to check the contents of matrix elements in C plugin

From   [email protected] (Alan Riley)
To   [email protected]
Subject   Re: st: How to check the contents of matrix elements in C plugin
Date   Tue, 25 Apr 2006 22:28:23 -0500

Lei Xuan ([email protected]) is trying to write a C plugin
for Stata.  Lei is having trouble with some example code from the
Stata web site:
> I copied a piece of C code from online Section 8b, 8d.
> to test -SF_mat_el()-.  My question is how I can see/check the contents of
> matrix elements.
> If I included the following code, given in Section 8d for debugging and
> printing out results, the C compiler reported errors (I use Microsoft Visual
> C++ 6). I changed "snprintf" to "sprintf", errors are gone, but warnings are
> still there. 

Lei started with code that had the following function call in it:

    snprintf(buf, 80, "The value of z is %lf\n",z);

Lei is using Microsoft Visual C++ and reported that the compiler
complained that snprintf() could not be found.  Lei then switched
the code to use sprintf() and got it to compile, but found that the
resulting plugin would crash Stata.

Kristin MacDonald ([email protected]) and Yulia Marchenko
([email protected]) investigated Lei's problem and sent a private
response which should solve the issue for Lei.  I'll post the results
here for any other Statalist members who may be interested, and to put
an answer in the Statalist archives for future reference.

When Lei replaced snprintf() with sprintf(), the line in question
looked like

    sprintf(buf, 80, "The value of z is %lf\n",z);

snprintf() is a C function similar to sprintf(), but which takes
an extra argument for safety which limits the amount of data which
will be put in 'buf'.

sprintf() does not take such an argument.  Visual C++ compiled the
line of code anyway, issuing a warning about an argument to sprintf()
not matching the expected type for that argument.  At execution time,
however, a crash occurred.  The quick fix was to remove the length
argument of '80' from the call to sprintf():

    sprintf(buf, "The value of z is %lf\n",z);

For those interested in why snprintf() would not work for Lei, Microsoft
only defines this function with a leading underscore: _snprintf():

Thus, Lei also could have used

    _snprintf(buf, 80, "The value of z is %lf\n",z);

([email protected])
*   For searches and help try:

© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index