HP C/aC++ for PA-RISC Software manual +check=malloc

Page 79

void *thread2(void *arg) { pthread_mutex_lock(&mutex2); things_done++; pthread_mutex_unlock(&mutex2); return 0;

}

int main(int argc, char *argv[])

{

pthread_t th1, th2;

pthread_create(&th1, NULL, thread1, (void*)NULL ); pthread_mutex_lock(&mutex1);

things_done++;

pthread_mutex_unlock(&mutex1);

pthread_create(&th2, NULL, thread2, (void*)NULL ); sleep(10);

return 0;

}

cc+check=lock simple_race.c -lpthread

./a.out

Runtime Error: locking discipline violation: in file simple_race.c line 16 address 40010658

(0)0x0000000004072ca0 _rtc_raise_fault + 0x2c0 at rtc_utils.c:382 [./a.out]

(1)0x0000000004028650 _ZN11DRD_Runtime15HandleMemAccessEybPcjS0_ + 0x590 at lock_check.C:438 [./a.out]

(2)0x0000000004029840 _ZN11DRD_Runtime17HandleStoreAccessEyPcjS0_ + 0x60 at lock_check.C:145 [./a.out]

(3)0x000000000401bfa0 __DRD_RegisterStoreAccess__ + 0x160 at lock_check.H:126 [./a.out]

(4)0x0000000004018780 thread2 + 0xd0 at simple_race.c:16 [./a.out]

(5)0x60000000c57c3c60 __pthread_bound_body + 0x170

at /ux/core/libs/threadslibs/src/common/pthreads/pthread.c:4512 [/proj/thlo/Compilers/rt/usr/lib/hpux32/libpthread.so.1]

candidate lockset is as follows: lock1.c line number:23

incoming lockset is as follows: lock1.c line number:13

In the above message, the candidate lockset refers to the set of locks that are implied to be associated with the symbol acesss in its previous accesses so far. The incoming lockset refers to the set of locks that are held at the current access of the symbol. When the intersection between the candidate lockset and incoming lockset is empty, the checker reports the locking discipline violation. The candidate lockset and incoming lockset members are specified in terms of the source file and line number pointing to the pthread_mutex_lock call associated with that lock. For further details on detecting lock discipline violations, refer to the above-referenced Eraser article.

False positives are possible in certain cases, as mentioned in the Eraser article. Multiple locks can be used to protect the same shared variable. For example, a linked list can be protected by an overall lock and an individual entry lock. This can result in the tool reporting a false positive. False positives might also be reported as a result of memory getting recycled in certain cases because of deallocations (which the lock checker is not able to detect).

+check=malloc

The +check=malloc option enables memory leak and heap corruption checks at runtime. It will cause the user program to abort for writes beyond boundaries of heap objects, free or realloc calls for a pointer that is not a valid heap object, and out-of-memory conditions. Memory leak information is captured and written out to a log file when the program exits. The name of the logfile is printed out before program termination.

The +check=malloc option works by intercepting all heap allocation and deallocation calls. This is done by the use of a debug malloc library, librtc.so. The option works for programs that use the system malloc or for user provided malloc routines in a shared library. The librtc.so library is also used by the HP WDB debugger to provide heap memory checking features in the debugger. Please refer to the HP WDB debugger documentation for more information about heap memory checking. The librtc.so library is shipped as part of the wdb product.

Runtime Checking Options 79

Image 79
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Data Alignment Pragmas Pragma Directives and AttributesInitialization and Termination Pragmas Copyright Notice and Identification PragmasContents Preprocessing Directives 119 Standardizing Your Code 138 Using HP aC++ Templates 132Exception Handling 161 Optimizing HP aC++ Programs 156170 Tools and Libraries 175Mixing C++ with Other Languages 188 Migrating from HP C++ cfront to HP aC++ 198 Distributing Your C++ Products 195Strings 194 Arrays Files in Fortran Glossary 223 Index 227 Documentation feedback 221 Diagnostic Messages 222HP secure development lifecycle Intended Audience About This DocumentWhat’s in This Document This document uses the following conventions Typographical ConventionsHP-UX 11i Releases Publishing HistoryRelated Documents HP-UX Release Name and Release IdentifierFollowing is a list of documents available with this release HP Encourages Your CommentsOther HP aC++ executable files are Getting Started with HP aC++Components of the Compilation System C89 C99 ecom CtcomDebugging Programs Using the aCC CommandCompiling a Simple Program Executing the ProgramExamples of the aCC Command Compiler Command Syntax and Environmental VariablesPreprocessed Source Files .i Files Files on the aCC Command LineAssembly Language Source Files .s Files ++ Source File .C fileLibrary Files .a and .so Files Configuration Files .conf FilesEnvironment Variables Object Files .o FilesCclibdir Environment Variable ACCFULLPATHNAMES Environment VariableACCMAXERR Environment Variable Cxxopts Environment VariableACC -L/mnt/proj/lib file.o ACC file.o Ccrootdir Environment VariableExport CCROOTDIR=/mnt/CXX2.1 Floating InstallationCxxmapfile Environment Variable Tmpdir Environment VariableHP aC++ Setting up Floating InstallationCommand-Line Options ILP32 Data Model and LP64 Data Model Options to Control Code GenerationACC -c sub.C prog.C ACC +DO11.22 +O3 app.CCompiling in Networked Environments Using +DS to Specify Instruction SchedulingACC -S prog.C Data Alignment and StorageSize and Alignment of HP Compiler Data Types ACC +u1 app.C Debugging OptionsFshort-enums +expandtypesindiag+macrodebug When to use -g, -g0, and -g1Differences Between -g, -g0, and -g1 Options G1 AlgorithmLocal +noobjdebug+pathtrace +pathtrace=kindACC +p file.C Error HandlingNone +pathtrace=globallocal+Wargs +wn+Wcontextlimit +Wv +wperfadvice+We +Weargs+noeh Exception HandlingExtensions to the Language +wsecurityFloating-Point Processing Options +Onofenvaccess+Onocxlimitedrange +decfp FpevalFpevaldec Nofpwidetypes+Onopreservedfpregs +FPmode+Onolibmerrno +OprefetchlatencyHeader File Options ACC -I include file.C Idirs -I- -Idirs +help Online Help Option+inlinelevel num Inlining OptionsLname Library OptionsDynamic Exec+Onolibcalls= Linker OptionsMinshared +nostl+Onodynopt UsymbolUsymbol +Onodynopt+ildrelink Options for Naming the Output FileNative Language Support Option +ildACC -z file.C Handling Null Pointers OptionsCode Optimizing Options Basic Optimization Level Options+O3 +O0+O1 +O2+O4 Additional Optimization Options for Finer Control+O4 ACC +O3 prog.C+nonrv Ipo+Onofailsafe +Onoptrstoglobals=list Advanced +Ooptimization Options+Onoaggressive +Onolimit+Onofltacc +Onocrossregionaddressing+Onodatalayout +Onodataprefetch+Onoinitcheck +Ofrequentlycalled+Olit +Onoinline+Ointegeroverflow +Onoopenmp +Olevel+Onolooptransform +Onoloopunroll+Onoprocelim +opts+Onoparminit +Onoparmsoverlap+Onosignedpointers +Orarelycalled+Oshortdata +Ounrollfactor +OtypesafetyProfile-Based Optimization Options +OnostoreorderingAnnotate=structs Parallel Processing OptionsInformation Embedding Options Displaying Optimization InformationRequired if -DPOSIXCSOURCEis used Option Matrix for -mt+tls=staticdynamic +Onoautopar+Ofast Performance Options+wlock Fast+DSmodel +Ofaster+Onotlscallschangetp +nosrcpos+uc Porting Options+sb +ubThis warning can be suppressed by adding an extra cast +w64bit+wdriver +wendianDname Preprocessor OptionsRedirecting Output From This Option Examples Maked+Maked +makedUname Profiling Code Options+profilebucketsize +check=none Runtime Checking Options+check +check=allCompiling with +check=boundspointer +check=boundsarray +check=boundspointerCheck off by any number out-of-bounds access Check off by one out-of-bounds access+check=lock +check=globals+check=malloc +check=thread +check=stackframevariablesnone+check=truncateimplicit +check=truncateexplicitimplicit+check=uninit Ch = intval & 0xff +check=truncateexplicitAarm Standards Related OptionsAarm Agcc AC89AC99 Ag+++legacycpp AOa and -AOe+legacyv5 +stl=rwnone +std=c89c99c++98c++11gccg++gnu+tru64 +tru64Wc,-ansiforscope,onoff Wc,-koeniglookup,onoffTx,name Subprocesses of the CompilerTx,name More Examples of -tWx,args Passing Options to the Linker with -W Symbol Binding OptionsBdefault BexternBprotecteddata BhiddenBhiddendef BprotectedTemplate Options +instincludesuffixes Trigraph Processing Suppression OptionVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r ACC -V app.C Concatenating OptionsACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas #pragma align N Data Alignment Pragmas#pragma Versionid string #pragma Versionid Software Product, Version 12345.A.01.05Data Alignment Pragmas Template Example Basic ExampleHandling Unaligned Data Implicit Access to Unaligned DataInteraction between pack and unalign pragmas is as follows #pragma unalign Typedef T1 T2Floattrapson Pragma Optimization PragmasOptlevel Pragma Optimize PragmaNoinline Pragma Other Pragmas Diagnostic PragmasExtern Pragma Defaultbinding PragmaBinding Pragma Estimatedfrequency PragmaHpdefinedinternal Pragma Hdrstop PragmaHidden Pragma Hpdefinedexternal PragmaPtrsstronglytyped Pragma POP PragmaPragma once Protected PragmaStdc Fpcontract Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc Cxlimitedrange Pragma Stdc FLOATCONSTDECIMAL64 PragmaUnrollfactor Pragma Stdc Fenvaccess PragmaOMP Atomic Pragma OMP Flush Pragma OMP Barrier PragmaOMP Critical Pragma OMP for PragmaOMP Parallel for Pragma OMP Master PragmaOMP Ordered Pragma OMP Parallel PragmaOMP Task Pragma OMP Parallel Sections PragmaOMP Sections Pragma OMP Single PragmaOpenMP Clauses Copyin DefaultCopyprivate SharedAttributes Attribute noreturn Attribute nonexposingAttribute noreturn Attribute nonexposingAttribute visibility Attribute formatAttribute warnunusedresult Usage Guidelines Preprocessing DirectivesOverview of the Preprocessor SyntaxAssertions #assert, #unassert Source File Inclusion #include, #includenextSyntax DescriptionMacros with Parameters Macro Replacement #define, #undef#define mac very very long\ Replacement string ExamplesFollowing illustrates the ## operator Specifying String Literals with the # OperatorConcatenating Tokens with the ## Operator Example#define Arraysize 1000float xARRAYSIZE Using Macros to Define ConstantsOther Macros Var1 isUsing Constants and Inline Functions Instead of Macros Predefined Macros Assertions #assert, #unassertHP aC++ predefines the following predicates Conditional Compilation #if, #ifdef, .. #endifCode that compiles if the expression evaluates to zero Using the #else Directive Using the defined OperatorUsing the #if Directive Using the #ifdef and #ifndef DirectivesExample Line Control #line#line 5 myfile See page 96 for more information on pragmas This macro enables the following non-standard featuresIostream Performance Improvement Pragma Pragma Directive #pragma and Pragma OperatorLine below contains the trigraph sequence ??= Error Directive #errorTrigraph Sequences Examples??=line 5 myfile When this line is compiled it becomesTemplate Processing Using HP aC++ TemplatesInvoking Compile-Time Instantiation Scope and PrecedenceTemplate class Tablechar Explicit InstantiationUsage PerformanceACC -c +instcompiletime a.C ACC -c a.C Command-Line Option InstantiationCompile-Time Instantiation Function TemplateScope Why Use Compile-Time InstantiationPossible Duplicate Symbols in Shared Libraries Possible Duplicate Symbols in Archive LibrariesBuilding an Archive Library with Compile-time Instantiation ++ Template TutorialClass Templates Building an Archive Library with +instauto/+instcloseFunction Templates HP aC++ Keywords Standardizing Your CodeHP aC++ Keywords Bool KeywordDynamiccast Keyword Compile time error message isAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Connections Across Translation Units Namespace and using KeywordsInt Using- declarations and using- directivesUsing Nx // Where N is a namespace, x is a name in N An Auxiliary Translation UnitPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Template Keyword Wchart KeywordTypename Keyword Use it as the name of the template C below Overloading new and delete for ArraysDeclare a class as a member of the class template C2 below Example Standard Exception Classes RangeerrorInvalidargument Typeinfo Class Exceptions Thrown by the Standard C++ LibraryFollowing exceptions are thrown by the Standard C++ Library Int before const typeinfo& const Unsupported FunctionalityMemfun1reft Memfunreft Iostream Level 1 Optimization Setting Basic Optimization LevelsOptimizing HP aC++ Programs Requesting OptimizationEnabling Aggressive Optimizations Additional Options for Finer ControlLevel 3 Optimization Level 4 OptimizationLimiting the Size of Optimized Code Removing Compilation Time Limits When OptimizingProfile-Based Optimization Enabling Only Conservative OptimizationsSample.exe input.file1 Sample.exe input.file2 InstrumentationCollecting Data for Profiling Maintaining Profile Data FilesSee Optimization Pragmas page 103 for more information Pragmas That Control OptimizationPerforming Profile-Based Optimization ACC -o sample.exe +Oprofile=use +O3 sample.CException Handling in C++ Exception HandlingFunction Try Block Examples Basic Exception Handling ExampleRogue Wave Standard C++ Library Using ThreadsUsing Locks Debugging Exception Handling Performance ConsiderationsLpthreadThis option applies only to kernel threads Required Command-line OptionsRogue Wave Standard C++ Library Rogue Wave Standard C++ Library 1.2.1 and Tools.h++Cout endl Using -DTHREADSAFE with the cfront Compatible libstreamUsing -DHPACCTHREADSAFERBTREE LimitationsException Handling Pthreads Posix ThreadsACC -mt prog.c Function Scoping Parallel Programming Using OpenMPOpenMP Implementation OpenMP Library OpenMP Header FileOpenMP APIs are defined in the library libomp Where, kind is either of of static, dynamic, or guided +Onoopenmp Command Line OptionEnvironment Variables in OpenMP Openmp MacroExport OMPNESTED=value Setenv Ompnested value Runtime Library Functions in OpenMPExecution Environment Functions Export OMPDYNAMIC=value Setenv Ompdynamic valueOmpgetthreadnum OmpsetnumthreadsOmpgetnumthreads OmpgetmaxthreadsOmpsetnested Lock FunctionsOmpsetdynamic OmpgetdynamicOmpunsetlock and ompunsetnestlock Ompinitlock and ompinitnestlockOmpdestroylock and ompdestroynestlock Ompsetlock and ompsetnestlockOmpgetwtick Timing FunctionsOmptestlock and omptestnestlock Functions OmpgetwtimeLocale directive for lex HP Specific Features of lex and yaccCreating and Using Libraries Tools and LibrariesIntroduction Introduction to Using the Standard C++ LibraryHP aC++ Libraries Standard C++ LibraryNon-Object-Oriented Design of the Standard C++ Library Differences between Standard C++ Library and Other LibrariesIncompatibilities Between the Library and the Standard Standard C++ Library ReferenceIOStream Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cTools.h++ Library HP aC++ Runtime Support LibrarySpecifying Other Libraries Creating and Using Shared LibrariesLinking to C++ Libraries Linking with Shared or Archive LibrariesLinking Archive or Shared Libraries Using a Shared LibraryExample of Creating and Using a Shared Library Creating a Shared LibraryForcing the Export of Symbols in main Advanced Shared Library FeaturesUpdating a Shared Library Linker Options to Manage Shared Libraries Binding TimesSide Effects of C++ Shared Libraries Routines and Options to Manage C++ Shared LibrariesAllocation Policies for Containers Standard HP-UX Libraries and Header FilesFor a string type For -AA Standard LibraryHP aC++ Executable Files HP aC++ File LocationsUsr/lib/hpux##/libCsup.so HP aC++ Runtime Libraries and Header FilesUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant Calling Other Languages Mixing C++ with Other LanguagesData Compatibility between C and C++ Examples of extern C Using the extern C Linkage SpecificationHP aC++ Calling HP C Syntax of extern CMain Function Differences in Argument Passing ConventionsExamples HP aC++ Calling HP C Running the Example HP C Calling HP aC++Enter the nameJoann Joann has a balance Compiling and Running the Sample Programs To compile the example, run the following commandsExample of Reference Variables as Arguments Using Reference Variables to Pass ArgumentsCalling HP Fortran 90 from HP aC++ Function Naming ConventionsFiles in Fortran Using extern C LinkageStrings ArraysApplications that use HP aC++ Shared Libraries Distributing Your C++ ProductsLinking Your HP aC++ Libraries with Other Languages Installing your ApplicationHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files CC +p cfrontfile.C Migrating from HP C++ cfront to HP aC++General Guidelines for Migration Getting Started with MigrationExplicit Loading and Unloading of Shared Libraries Command-Line DifferencesNew Command-Line Options Writing Code for both CompilersDescribes obsolete command-line options for HP aC++ Obsolete Command-Line OptionsPtv Changed Command-Line OptionsSee Debugging Options page 35 for complete information Migration Considerations when DebuggingMigration Considerations when Using Exception Handling Exception Handling is the DefaultMemory Allocation Failure and operator new Possible Differences when Exiting a Signal HandlerCalling unexpected Differences in setjmp/longjmp BehaviorThrowing an Object having an Ambiguous Base Class Unreachable catch ClausesStandards Based Libraries Migration Considerations when Using LibrariesMan 3s filebuf HP C++ cfront Compatibility LibrariesFstream3C++ iostream and streambuf specialized to files Manip3C++ iostream manipulatorsReplace #include with complex Migration Considerations Related to PreprocessingHP C++ cfront Complex Library Not Supported HP C++ cfront Task Library Not SupportedImplicit Typing of Character String Literals Migration Considerations Related to StandardizationObsolete Preprocessor Options Changes in C++ SemanticsExecution Order of Static Constructors in Shared Libraries Overload Resolution Ambiguity of Subscripting OperatorMore Frequent Inlining of Inline Code Changes in C++ SyntaxExplicit int Declaration WC,-ansiforscope,on For Statement, New Scoping RulesStruct as Template Type Parameter is Permitted Equivalent, valid HP aC++ code followsOverload not a Keyword This code compiles without error with HP aC++Base Template Class Reference Syntax Change Tokens after #endifStatic Member Definition Required Dangling Comma in enumDeclaring friend Classes Ambiguous Function or Object Declaration Using in Class DefinitionsIncorrect Syntax for Calls to operator new Duplicate Formal Argument NamesReference Initialization Overloaded Operations ++Parentheses in Static Member Initialization List Using operator new to Allocate ArraysOn HP aC++, the following error is generated Compiling this code HP aC++ generates the following errorNon-constant Reference Initialization Qualified-id Required in Static Member Initialization ListCA a Migration Considerations when Using TemplatesVerbose Template Processing Information Digraph White Space SeparatorsCommon Template Migration Syntax Changes Converting Directed Mode to Explicit InstantiationCfront Implicit Include Convention Documentation feedback AC++ Message Catalog Diagnostic MessagesFrequently Encountered Messages Aggressive GlossaryInternational Standard defines only synchronous exceptions See template Glossary Index SymbolsCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb