The media on which you receive National Instruments software are warranted not to fail to execute programming
instructions, due to defects in materials and workmanship, for a period of 90 days from date of shipment, as evidenced
by receipts or other documentation. National Instruments will, at its option, repair or replace software media that do not
execute programming instructions if National Instruments receives notice of such defects during the warranty period.
National Instruments does not warrant that the operation of the software shall be uninterrupted or error free.
A Return Material Authorization (RMA) number must be obtained from the factory and clearly marked on the outside
of the package before any equipment will be accept ed for warranty work. National Instru ments will pay the shippi ng costs
of returning to the owner parts which are covered by warranty.
National Instruments believes that the informatio n in this manual is accurate. The docume nt has been ca refully review ed
for technical accurac y. In th e even t that te ch nical o r typograp hic al errors exis t, Nation al Inst ruments rese rves th e right to
make changes to subsequent editions of this document without prior notice to holders of this edition. The reader should
consult National Instruments if errors are suspected. In no event shall National Instruments be liable for any damages
arising out of or related to this document or the information contained in it.
XCEPT AS SPECIFIED HEREIN
E
ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
BY FAULT OR NEGLIGENCE ON THE PART OF NATIONAL INSTRUMENTS SHALL BE LIMITED TO THE AMOUNT THERETOFORE PAID BY THE
CUSTOME R
OR INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN IF ADVISED OF THE POSSIBILITY THEREOF
National Instruments will apply regardless of the form of action, whether in contract or tort, including negligence.
Any action against National Instruments must be brought within one year after the cause of action accrues. National
Instruments shall not be liable for any delay in performance due to causes beyond its reasonable control. The warranty
provided herein does not cover damages, defects, malfunctions, or service failures caused by owner’s failure to follow
the National Instruments installation, operation, or maintenance instructions; owner’s modification of the product;
owner’s abuse, misuse, or negligent acts; and power failure or surges, fire, flood, accident, actions of third parties, or
other events outside reasonable control.
ATIONAL INSTRUMENTS WILL NOT BE LIABLE FOR DAMAGES RESULTING FROM LOSS OF DATA, PROFITS, USE OF PRODUCTS
. N
ATIONAL INSTRUMENTS MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AND SPECIFICALLY DISCLAIMS
, N
Copyright
Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical,
including photocopyi ng, recordi ng, st oring in an info rmation ret riev al syste m, or translating , in whole or in part, wit hout
the prior written consent of National Instruments Corporation.
USTOMER’S RIGHT TO RECOVER DAMAGES CAUSED
. C
. This limitation of the liability of
,
Trademarks
CVI™, National Instruments™, the National Instruments logo, natinst.com™, and The Software is the Instrument™are
trademarks of National Instruments Corporation.
Product and company names listed are trademarks or trade names of their respective companies.
WARNING REGARDING MEDICAL AND CLINICAL USE OF NATIONAL INSTRUMENTS PRODUCTS
National Instruments products are not designed with components and testing intended to ensure a level of reliability
suitable for use in treatment and diagnosis of humans. Applications of National Instruments products involving medical
or clinical treatment can create a potential for accidental injury caused by product failure, or by errors on the part of the
user or application des igner. Any us e or ap plica tion of Na tiona l Instrum ents pr oducts for or inv olving m edi cal or clin ica l
treatment must be performed by properly trai ned and qualifi ed medic al pe rsonne l, and al l tra ditiona l medic al safegu ards,
equipment, and procedu res that are appropriate in the particula r situation to prevent serious injury or dea th should al ways
continue to be used when Natio nal Instrume nts products are being use d. National In struments prod ucts are N OT intended
to be a substitute for any form of establis hed process, procedure, or e quipment us ed to monit or or safeguard human heal th
and safety in medical or clinical treatment.
Contents
About This Manual
Organization of This Manual................................................ ...... ..... ................................xiii
Conventions Used in This Manual...................................................................................xiv
Related Documentation.....................................................................................xv
The LabWindows/CVI Programmer Reference Manual contains
information to help you develop programs in LabWindows/CVI. The
LabWindows/CVI Programmer Reference Manual is intended for use by
LabWindows users who have already completed the Getting Started with LabWindows/CVI tutorial. To use this manual effectively, you should be
familiar with Getting Started with LabW i ndows/CVI, the LabW indows/CVI User Manual, DOS, Windows, and the C programming language.
Organization of This Manual
The LabWindows/CVI Programmer Reference Manual is organized as
follows:
compiler specifics, C language extensions, 32-bit compiler issues,
debugging levels, and user protection.
•Chapter 2, Using Loadable Compiled Modules, describes the
advantages and disadv antages of using compiled code modules in your
application. It also describes the kinds of compiled modules available
in LabWindows/CVI and includes programming guidelines for
modules you generate with external compilers.
•Chapter 3, Windows 95/NT Compiler/Linker Issues, describes the
different kinds of compiled modules available under
LabWindows/CVI for Wi nd ows 95/NT and includes programming
guidelines for modules you generate with external compilers.
•Chapter 4, Windows 3.1 Compiler/Linker Issues, describes the
different kinds of compiled modules available under
LabWindows/CVI for Windows 3.1 and includes programming
guidelines for modules you generate with external compilers.
•Chapter 5, UNIX Compiler/Linker Issues, describes the kinds of
compiled modules available under LabWindows/CVI for UNIX and
includes programming guidelines for modules you generate with
external compilers.
•Chapter 6, Buildin g Multiplatform Applications, contains guidelines
and caveats for writing platform-independent LabWindows/CVI
applications. LabWindows/CVI currently runs under Windows 3.1
and Windows 95/NT for the PC, and Solaris 1 and Solaris 2 for the
SPARCstation.
National Instruments CorporationxiiiLabWindows/CVI Programmer Reference Manual
About This Manual
• Chapter7, Creating and Distributing Standalone Executables and
DLLs, describes how the LabWindows/CVI Run-time Engine, DLLs,
externally compiled modules, and other files interact with your
executable file. This chapter also describes how to perform error
checking in a standalone executable program. You can create
executable programs from any project that runs in the
LabWindows/CVI environment.
• Chapter8, Distributing Li braries andFuncti on Panels, describes how
to distribute libraries, add libraries to a user’s Library menu, and
specify library dependencies.
• Chapter9, Checking for Errors in LabWindows/CVI, describes
LabWindows/CVI error checking and how LabWindows/CVI reports
errors in LabWindows/CVI libraries and compiled external modules.
•AppendixA, Errors and Warnings, contains an alphabetized list of
compiler warnings, compiler errors, link errors, DLL loading errors,
and external module loading errors generated by LabWindows/CVI.
•AppendixB, Customer Communication, contains forms to help you
gather the information necessary to help us solve your technical
problems and a form you can use to comment on the product
documentation.
•The Glossary contains an alphabetical list of terms used in this manual
and a description of each.
•TheIndex contains an alphabetical list of key terms and topics used in
this manual, including the page where each one can be found.
Conventions Used in This Manual
The following conventions are used in this manual.
<> Angle brackets enclose the name of a key on the keyboard—for example,
<Shift>.
- A hyphen between two or more key names enclosed in angle brackets
denotes that you should simult aneously press the na med keys—for
example, <Ctrl-Alt-Delete>.
» The » symbol leads you through nest ed menu items and dial og box options
to a final action. The sequence File»Page Setup»Options» Substitute Fonts directs you to pull down the File menu, select the PageSetup item,
select Options, and finally select the Substitute Fonts options from the
last dialog box.
This icon to the left of bold italicized text denotes a note, which alerts you
to important information.
!
boldBold text denotes the names of menus, menu items, parameters, or dialog
bold italicBold italic text denotes an activity objective, note, caution, or warning.
italicItalic text denotes variables, emphasis, a cross reference, or an introduction
monospaceText in this font denotes text or characters that you should literally enter
monospace boldBold text in this font denotes the messages and responses that the computer
monospace italic
pathsPaths in this manual are denoted using backslashes (\) to separate drive
This icon to the left of bold italicized text denotes a caution, which advises
you of precautions to take to avoid injury, data loss, or a system crash.
box buttons.
to a key concept. This font also denotes text from which you supply the
appropriate word or value.
from the keyboard, sections of code, programming examples, and syntax
examples. This font is also used for the proper n ames of disk d ri ves, p aths,
directories, programs, functions, filenames and extensions, and for
statements and comments taken from programs.
automatically prints to the screen.
Italic text in this font denotes that you must enter the appropriate words or
values in the place of these items.
names, director i es, fol ders, and files .
Related Documentation
You may find the following documentation helpful while programming in
LabWindows/CVI:
•Microsoft Developer Network CD, Microsoft Corporation,
Redmond WA
•Programmer’s Guide to Microsoft Windows 95, Microsoft Press,
Redmond WA, 1995
•Harbison, Samuel P. and Guy L. Steele, Jr., C: A Reference Manual,
Englewood Cliffs, NJ: Prentice-Hall, Inc., 1995
National Instruments CorporationxvLabWindows/CVI Programmer Reference Manual
About This Manual
Customer Communication
National Instruments wants to recei v e you r comments on our p roducts and
manuals. We are interested in the applications you develop with our
products, and we want to help you if you have problems with the m. To
make it easy for you to contact us, this manual contains comment and
technical support forms for you to complete. These forms are in
Appendix B, Customer Communication, at the end of this manual.
This section describes specific LabWindows/CVI compiler limits, options, defines, and
diversions from the ANSI C standar d.
1
Compiler Limits
Table 1-1 shows the compiler limits for LabWindows/CVI.
Table 1-1.
Coding AttributeLimit
Maximum nesting of #include32
Maximum nesting of #if, #ifdef16
Maximum number of macro parameters32
Maximum number of function parameters64
Maximum nesting of compound blocks32
Maximum size of array/struct types2
National Instruments Corporation1-1LabWindows/CVI Programmer Reference Manual
LabWindows/CVI Compiler Limits
31
Chapter 1LabWindows/CVI Compiler
Compiler Options
Y ou can set the LabW indows/CVI compiler options by selecting Options»Compiler Opti ons
in the Project window. This command opens a dialog box that allows you to set
LabWindows/CVI compiler options. For a discussion of these options, refer to the Compiler Options section in Chapter 3, Project Window, of the LabWindows/CVI User Manual.
Compiler Defines
The LabWindows/CVI compiler accepts compiler defines through the Compiler Defines
command in the Options menu of the Project window. For more information, refer to the
Compiler Defines section in Chapter 3, Project Window, of the LabWindows/CVI User
Manual.
C Language Non-Conformance
LabWindows/CVI for UNIX does not allow you to pass a struct as one of a series of
unspecified variable arguments. Because of this,
LabWindows/CVI if
type is a struct type.
va_arg (ap, type) is not legal in
LabWindows/CVI accepts the
#line preprocessor directive, but ignores it.
C Language Extensions
The LabWindows/CVI compiler has several extensions to the C language. The purpose is to
make the LabWindows/CVI compiler compatible with the commonly used C extensions in
external compilers under Windows 95/NT.
Keywords That Are Not ANSI C Standard
LabWindows/CVI f or Windo ws 3.1 accepts the non-ANSI C keywords pascal, PASCAL, and
_pascal, but ignores them.
Calling Conventions (Windows 95/NT Only)
You can use the following calling convention qualifiers in function declarations:
cdecl
_cdecl
__cdecl
_stdcall
__stdcall
In Microsoft Visual C/C++, Borland C/C++, and Symantec C/C++, the calling convention
normally defaults to __
(recommended)
(recommended)
cdecl if you do not use a calling convention qualifier. You can,
however, set options to cause the calling convention to default to __stdcall. The behavior
is the same in LabWindows/CVI. Y ou can set the default calling conv ention to either __
__stdcall using the Compiler Options command in the Options menu of the Project
or
window. When you create a new project, the default calling convention is
__cdecl.
cdecl
In Watcom C/C++, the default calling convention is not __
-4s (80486 Stack-Based Calling) op tio n when you compil e a module in Watcom for
use the
cdecl or __stdcall. You must
use in LabWindows/CVI. Refer to the Compatibility with External Compilers section in
Chapter 3, Windows 95/NT Compiler/Linker Issues. The
-4s option causes the stack-based
calling convention to be the default. In LabWindows/CVI under W atcom compatibility mode,
the default calling con vention is always the stack-based con vention. It cannot be chan ged. The
LabWindows/CVI compiler accepts the
Watcom, except that floating point and structure return values do not work in the
calling convention. National Instruments recommends that you avoid using
__cdecl and __stdcall conventions under
__cdecl
__cdecl with
Watcom.
__cdecl calling convention and the Watcom stack-based calling convention, the
In the
calling function is responsible for cleaning up the stack. Functions can have a variable number
of arguments.
__stdcall calling convention, the called function is responsible for cleaning up the
In the
stack. Functions with a variable number of arguments do not work in
__stdcall qualifier on a function with a variable number of arguments,
the
__stdcall. If you use
LabWindows/CVI does not honor the qualifier. All compilers pass parameters and return
values in the same way for
__stdcall functions, except for floating point and structure
return values.
National Instruments recommends the
__stdcall calling convention for all functions
exported from a DLL, except functions with a variable number of arguments. Visual Basic
and other non-C Windows programs expect DLL functions to be
__stdcall.
Import and Export Qualifiers
You can use the following qualifiers in variable and function declarations:
National Instruments Corporation1-3LabWindows/CVI Programmer Reference Manual
Chapter 1LabWindows/CVI Compiler
At this time, not all these qualifiers work in all external compilers. The LabWindows/CVI
cvidef.h include file defines the following macros, which are designed to work in each
external compiler.
DLLIMPORT
DLLEXPORT
An import qualifier informs the compiler that the symbol is defined in a DLL. Declarations
of variables imported from a DLL r equi r e import qualifiers , but function declarat i o ns do n ot .
An export qualifier is relevant only in a project for which the target type is Dynamic Link
Library. The qualifier can be on the declaration or definition of the symbol, or both. The
qualifier instructs the linker to include the symbol in the DLL import library.
C++ Comment Markers
You can use doub le slashes (/ /) to be gin a comment. The comment continues until the end of
the line.
Duplicate Typedefs
The LabWindows/CVI compiler does not report an error on multiple definitions of the same
typedef identifier, as long as the definitions are identical.
Structure Packing Pragma (Windows 3.1 and Windows 95/NT Only)
The packpragma can be used within LabWindows/CVI to specify the m aximum alignment
factor for elements within a structure. For exam ple, assume the following structur e definition:
struct t {
double d1;
char charVal;
short shortVal;
double d2;
};
If the maximum alignment is 1, the compiler can start the structure on any 1-byte boundary
and inserts no gaps between the structure elements.
If the maximum alignment is 8, the compiler must start the structure on an 8-byte boundary,
shortVal on a 2-byte boundary, and place d2 on an 8-byte boundary.
#pragma pack(4) /* sets maximum alignment to 4 bytes */
#pragma pack(8) /* sets maximum alignment to 8 bytes */
#pragma pack() /* resets to the default*/
The maximum alignment the compiler applies to a structure is based on the last pack
pragma
statement it sees before the definition of the structure.
Program Entry Points (Windows 95/NT Only)
Under Windows 95/NT, you can u se WinMain instead of main as the entry-point function to
your program. You might want to do this if you pl an to li nk your ex ecutable using an exte rnal
compiler. You must include
WinMain parameter list. The following is the prototype for WinMain with the W indo ws data
windows.h for the data types that normally appear in the
types reduced to intrinsic C types.
int __stdcall WinMain(void * hInstance, void * hPrevInstance,
char * lpszCmdLine int nCmdShow)
C Library Issues
This section discusses special considerations in LabWindows/CVI in the areas of low-level
I/O functions and the UNIX C library.
Chapter 1LabWindows/CVI Compiler
Using the Low-Level I/O Functions
Many functions in the UNIX libraries and the C compiler libraries for the PC are not ANSI C
Standard Library functions. In general, LabWindows/CVI implements the ANSI C Standard
Library. Under UNIX, you can call UNIX libraries for the non-ANSI C functions in
conjunction with LabWindows/CVI.
The low-level I/O functions
ANSI C Standard Library . Under UNIX, these functions are av ailable in the UNIX C library .
Refer to Chapter 5, UN IX Compiler /Linker Issues, for more information.
Under Windows, you can use these functions along with
The size of an enumeration type depends on the value of its enumeration constant.
In LabWindo ws/CVI, characters are
The types
float and double conform to 4-byte and 8-byte IEEE standard formats.
signed, unless you explicitly declare them unsigned.
Converting 16-Bit Source Code to 32-Bit Source Code
If you convert a LabWindows for DOS application to a LabWindows/CVI application, use
this section as a guide after you complete the steps in Chapter 12, Converting LabWindows for DOS Applications, of the Getting Started with LabWindows/CVI manual.
In general, if you make few assumptions about the sizes of data types, little difference exists
between a 16-bit compiler and a 32-bit compiler except for the lar ger capacity of integers and
the larger address space for arrays and pointers.
declares a 2-byte integer in a 16-bit compiler such as LabWindows for DOS. In contrast,
a 32-bit compiler such as LabWindows/CVI handles this code as a declaration of a 4-byte
integer. In most cases, this does not cause a problem and the conversion is transparent,
because functions that use 2-byte integers in LabWindows for DOS use 4-byte integers in
LabWindo ws/CVI. Howe ver , this con version does cause a problem when a prog ram performs
one of the following actions:
•Passes an array of 16-bit integers to a GPIB, VXI, or Data Acquisition (DAQ) function
If you use a 32-bit
int array to receive a set of 16-bit integers from a device,
LabWindows/CVI packs two 16-bit values into each element of the 32-bit array. Any
attempt to access the array on an element-by-element basis does not work. Declare the
array as
short instead, and make sure any type specifiers that refer to it have the [b2]
modifier when you pass them as an argument to a Formatting and I/O Library function.
•Uses an
For example, if yo u pass an
I/O Library, such as a
%i[b2] specifier, it does not work correctly. Remove the [b2] modifier, or declare the
variable as
Conver sely , if you pass a
without the
int variable in a way that requires it to be a 2-byte integer
int argument by address to a function in the Formatting and
Scan source or a Scan/Fmt target, and it matches a %d[b2] or
short.
short argument by address and it matches a %d or %i specifier
[b2] modifier, it does not work correctly. Add the [b2] modifier.
NoteThe default for %d is 2 bytes on a 16-bi t compil er and 4 bytes on a 32-bi t compil er.
In the same way, the default for
int is 2 bytes on a 16-bit compiler, and 4 bytes on
a 32-bit compiler. This is why you do not have to make any m odifications if the
specifier for a variable of type
int is %d without the b
All pointers are 32-bit offsets. LabWindows/CVI does not use the
n
modifier.
far pointers that have both
a segment selector and an offset, except in 16-bit Windows DLLs under Windows 3.1.
LabWindows/CVI for Windows 3.1 calls 16-bit DLLs through a special interface
LabWindo ws/CVI generates fro m the header file for the DLL. For more information, refer to
the Using 32-Bit Watcom Compiled Mod ule s under Windows 3.1 and 16-Bit Windows DLLs
sections in Chapter 4, Windows 3.1 Compiler/Linker Issues.
National Instruments Corporation1-7LabWindows/CVI Programmer Reference Manual
Chapter 1LabWindows/CVI Compiler
Debugging Levels
Y o u can compile the source modules in your app lication to include debu gging information. If
you do so, you can us e breakpo ints and view or modify v a riables and e xpres sions while y our
program is suspended. You set the debugging level by selecting Options»Run Option s in the
Project window. Refer to the Run Options section in Chapter 3, Project Window, of the LabWindows/CVI User Manual for information on debugging levels.
User Protection
User protection detects invalid program behavior that LabWindows/CVI cannot otherwise
detect during compilation. LabWindows/CVI reports such invalid program behavior as user
protection errors. When you set the debugging level to Standard or Extended,
LabWindows/CVI maintains extra information for arrays, structures, and pointers, and uses
the information at run time to determine the validity of addresses.
Two groups of user protection errors exist based upon two characteristics: severity level and
error cate gory. In each case, the ANSI C standard states that programs with these errors have
undefined behavior. The two severity levels are as follows:
•Non-Fatal errors include expressions that are likely to cause problems, but do not
directly affect program execution. Examples include b ad pointer ar ithmetic, attempts to
free pointers more than once, and comparisons o f pointers to different ar ray objects. The
expression is invalid and its behavior is undefined, but execution can continue.
•Fatal errors include expressions that LabWindows/CVI cannot execute without causing
major problems, such as causing a general protection fault. For example, dereferencing
an invalid pointer value is a fatal error.
Error categories include pointer protection, dynamic memory protection, library protection,
and general protection errors. Each of these categories includes subgroups as described in the
following sections.
Array Indexing and Pointer Protection Errors
The pointer protection errors catch invalid operations with pointers and arrays. In this section,
these errors are grouped by the type of expr ession that causes the error or the type of invalid
pointer involved.
Pointer Arithmetic (Non-Fatal)
Pointer arithmetic expressions involve a pointer sub-expression and an integer
sub-expression . LabWindows/CVI generates a n error when the pointer sub-expression is
invalid or when the arithmetic operation results in an invalid pointer expression. The
following user protection errors involve pointer arithmetic:
•Pointer arithmetic involving u ninitialized pointer
•Pointer arithmetic involving n ull pointer
•Out-of-bounds pointer arithmetic (calculation of an array address that results in a pointer
value either before the start, or past the end of the array)
•Pointer arithmetic involving pointer to freed memory
•Pointer arithmetic involving in valid pointer
•Pointer arithmetic involving address of non-array object
•Pointer arithmetic involving p ointer to function
•Array index too large
•Negative array index
Pointer Assignment (Non-Fatal)
LabWindows/CVI generates pointer assignment errors when you assign invalid values to
pointer variables. These warnings can help determine when a particular pointer becomes
invalid. The following user protection errors involve pointer assignment:
•Assignment of uninitialized pointer value
•Assignment of out-of-bounds pointer expression (assignment of an address before the
start, or past the last element, of an array)
•Assignment of pointer to freed memory
•Assignment of invalid pointer expression
Pointer Dereference Errors (Fatal)
Dereferencing of inv alid pointer v alues is a fatal error because it can cause a memory f ault or
other serious problem. The following user protection errors involve pointer dereferencing:
•Dereference of uninitialized pointer
•Dereference of null pointer
•Dereference of out-of-bounds po inter (dereference using a pointer valu e before the start,
or past the end, of an array)
•Dereference of pointer to freed memory
•Dereference of invalid pointer expression
•Dereference of data pointer for use as a function
National Instruments Corporation1-9LabWindows/CVI Programmer Reference Manual
Chapter 1LabWindows/CVI Compiler
•Dereference of a pointer to an n-byte type where less than n bytes exist in the object
•Dereference of unaligned pointer (UNIX only)
Pointer Comparison (Non-Fatal)
LabWindows/CVI generates pointer comparison errors for erroneous pointer comparison
expressions. The following user protection errors involve pointer comparison:
•Comparison involving uninitialized pointer
•Comparison involving null pointer
•Comparison involving invalid pointer
•Comparison of pointers to different objects
•Pointer comparison involving address of non-array object
•Comparison of pointers to freed memory
Pointer Subtraction (Non-Fatal)
LabWindows/CVI generates pointer subtraction errors for erroneous pointer subtraction
expressions. The following user protection errors involve pointer subtraction:
•Subtraction involving unin itialized pointer
•Subtraction involving null pointer
•Subtraction involving invalid pointer
•Subtraction of pointers to different objects
•Pointer subtraction involving address of non-array object
•Subtraction of pointers to freed memory
Pointer Casting (Non-Fatal)
LabWindows/CVI generates a pointer casting error when you cast a pointer expression to type
AnyType *) and not enough space exists for an object of type AnyType at the location the
(
pointer expression specifi es. This occurs only when casting a dynamically allocated object fo r
the first time, such as with the code
LabWindows/CVI reports the following error:
Dynamic memory protection errors report illegal operations with dyna mi c memory and
corrupted dynamic memory during allocation and deallocation.
Memory Deallocation (Non-Fatal)
LabWindows/CVI generates memory deallocation errors when the pointer is not the result of
a memory allocation. The following user protection errors involve memory deallocation:
•Attempt to free uninitialized pointer
•Attempt to free pointer to freed memory
•Attempt to free invalid pointer expression
•Attempt to free pointer not allocated with
Memory Corruption (Fatal)
LabWindows/CVI generates memory corruption errors when a memory
allocation/deallocation detects corrupted memory. During each dynamic memory operation,
LabWindows/CVI verifies the integrity of the memory blocks it uses in the operation. When
you set the Debuggi ng Level to Exten ded, LabWindo ws/C VI thor oughl y checks al l dynami c
memory on each memory oper ation. LabW in do ws/CVI generates the follo wing erro r when it
discovers a problem:
Dynamic memory is corrupt.
Chapter 1LabWindows/CVI Compiler
malloc or calloc
General Protection Errors
LabWindows/CVI also checks for stack overflow and missing return values:
•Stack overflow (fatal)
•Missing return value (non-fatal)
The missing return value error means that a non-void function (one you do not declare with
void return type) returned, but did not returned a value.
Library Protection Errors
Library functions sometimes generate errors when they receive invalid arguments.
LabWindows/CVI error checking is sensitive to the requirements of each library function.
The following errors involve library protection:
•Null pointer argument to librar y function
•Uninitialized pointer argument to library function
•Passing a pointer to freed memory to a library function
•Array argument too small
•Passing by reference a scalar argument to a library function that expects an array
National Instruments Corporation1-11LabWindows/CVI Programmer Reference Manual
Chapter 1LabWindows/CVI Compiler
•Missing terminating null in string argument
•Passing a string to a library function that expects a character reference parameter
LabWindows/CVI libr ary functions retu rn error codes in a v ariety of cases. If you enable the
Break on Library Errors option in the Run Options command in the Options menu of the
Project window , LabW indows/CVI suspends execution after a library function returns one of
these errors. A message appears that displays the name of the function and either the return
value or a string that explains why the function failed.
Disabling User Protection
Occasionally, you might want to disable user protection to avoid run-time errors that do not
cause problems in your program.
Disabling Protection Errors at Run-Time
You can use the SetBreakOnProtectionErrors function in the Utility Library to
programmatically control whether LabWindo ws/CVI suspends ex ecution when it encounters
a protection error. This function does not affect the Break on Library Errors feature.
Disabling Library Errors at Run-Time
The Break on Library Errors option in the Run Options command in the Options m enu of
the Project window lets you choose whether LabWindows/CVI suspends execution when a
library function returns an error code. The option takes effect when you start executing the
project. You can override the initial setting in your program by using the
SetBreakOnLibraryErrors function in the Utility Library. Use of this function does not
affect the reporting of other types of library protectio n errors.
Disabling Protection for Individual Pointer
You can disable pointer checking for a particular pointer by casting it first to an arithmetic
type and then back to its original type, as shown in the following macro:
char *charPointer;
/* run-time checking is performed for charPointer before this
line */
DISABLE_RUNTIME_CHECKING(charPointer);
/* no run-time checking is performed for charPointer after this
line */
This macro could be useful in the following situation: LabWindows/CVI reports erroneous
run-time errors because you set a pointer to d ynamic memory in a source module and you th en
resize it in an object module. The following steps describe how this error occurs:
1.Y o u declare a pointer in a source module you compile with debu gging enabled. You then
assign to the pointer an address that
AnyType *ptr;
ptr = malloc(N);
malloc or calloc returns:
2.You reallocate the pointer in an object module so that it points to the same location in
memory as before. This might occur if you call the
and then reassign it to memory that you allocate with
ptr = realloc(ptr, M); /* M > N */
realloc function or free the pointer
malloc:
or
free(ptr);
ptr = malloc(M);
3.You use the same pointer in a source module you compile with debugging enabled. At
this point, LabWindows/CVI still expects the pointer to point to a block of memo ry of
the original size
*(ptr+(M-1))/* This generates a fatal run-time error, */
(N).
/* even though it is a legal expression. */
To prevent this error, use the DISABLE_RUNTIME_CHECKING macro to disable checking for
the pointer after you allocate memory for it in the source module:
ptr = malloc(N);
DISABLE_RUNTIME_CHECKING(ptr);
Disabling Library Protection Errors for Functions
You can disable or enable library protection errors by placing pragmas in the source code.
LabWindo ws/CVI ignores t hese prag mas when y ou compil e without deb ugging informati on,
that is, if the debugging level is None. For example, the following two pragmas enable and
disable library checking for all the function declarations that occur after the pragma within a
header or source file. The pragmas affect only the functions declared in the file in which the
pragmas occur. These pragmas do not affect nested include files.
The following pragmas enable and disable library checking for a particular function. You
must declare the function before the occurrence of the pragma.
#pragma EnableFunctionRuntimeChecking function
#pragma DisableFunctionRuntimeChecking function
National Instruments Corporation1-13LabWindows/CVI Programmer Reference Manual
Chapter 1LabWindows/CVI Compiler
These two pragmas enable and disable run-time checking for a particular library function
throughout the module in which they appear. You can use them to override the effects of the
EnableLibraryRuntimeChecking and DisableLibraryRuntimeChecking pragmas
for individual functions. If both of these pragmas occur in a module for the same function,
LabWindows/CVI uses only the last occurrence.
NoteThese pragmas affect all protection, including run-time checking of function
arguments, for all calls to a specific library function. To disable breaking on
errors for a particular call to a library function, use the Utility Library function
SetBreakOnLibraryErrors. To disable the run-time checking of argument
expressions for a particular ca ll to a library function, use the Utility Library
function
NoteYou cannot use prag mas to disable protection for the functio ns in the
SetBreakOnProtectionErrors.
statically linked libraries including User Interface, RS-232, TCP, DDE,
Formatting and I/O, Utility, X Property, and ANSI C libraries unless you place the
DisableLibraryRuntimeChecking pragma at the top of the library header file.
Details of User Protection
Pointer Casting
A cast expression consists of a left parenthesis, a type name, a right parenthesis, and an
operand expression. The cast causes the compiler to convert the operand v alue to the type that
appears within the parenthesis.
C programmers occasionally have to cast a pointer to one data type to a pointer to another data
type. Because LabWindo ws/CVI does not restructure the user protection information for each
cast expression, certain types of cast expressions implicitly disable run-time checking for the
pointer value. In particular, casting a pointer expression to the following types disables
run-time checking on the resulting value:
•Pointer to a pointer:
(AnyType **) PointerExpression
•Pointer to a structure:(struct AnyStruct *) PointerExpression
LabWindows/CVI provides run-time error checking for pointers and arrays in dyna m ically
allocated memory.
You can use the ANSI C library functions
These functions return
void * values that you must cast to some other type before the
malloc or calloc to allocate dynamic memory.
memory can be used. During program execution, LabWindows/CVI uses the first such cast
on the return value of each call to these functions to determine the type of the object that will
be stored in the dynamic memory. Subsequent casts to different types can disable checking on
the dynamic data, as explained in the Pointer Casting discussion in this section.
You can use the
realloc function to resize dynamically allocated memory. This function
increases or decreases the size of the object associated with the dynamic memory.
LabWindows/CVI adjusts the user protection information accordingly.
Avoid Unassigned Dynamic Allocation in Function Parameters
The LabWindows/CVI run-time error checking mechanism dynamically allocates data to
keep track of pointers that you dynamically allocate in your program. When you no longer
use the pointers, LabWindows/CVI uses garbage collection to deallocate its corresponding
dynamic memory.
A case exists where the garbage collection fails to retrieve all the memory it allocated. This
occurs when you pass the return value of one function to another function, the return value is
a pointer to dynamically allocated memory, and you do not assign the pointer to a variable in
the argument expression. The following is an example:
MyFunc (1, 2, malloc(7));
This call passes the return value from malloc to MyFunc but does not assign it to a variable.
If you make this call repeatedly in your program with run-time checki ng enabl ed, you lose a
small amount of memory each time.
Change the code as follows to avoid this problem.
void *p;
MyFunc (1, 2, p = malloc(7));
The following code also works and uses better programming style.