Changes between Version 12 and Version 13 of Docs/Prog/Manual/ApplicationLibraries/lib825ev/String
- Timestamp:
- 04/12/23 15:40:22 (20 months ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Docs/Prog/Manual/ApplicationLibraries/lib825ev/String
v12 v13 13 13 In the above example the szMsg and szID character arrays are each allocated 10 bytes. C strings require a null character at the end to tell various functions such as strcpy when to stop reading characters. This means szMsg and szID can contain a maximum of 9 characters each. If the ''strcpy(szID, "123")'' is changed to ''strcpy(szID, "1234567890")'' the compiler will generate code that writes the null character into an invalid memory location. When the program is executed this may crash the indicator immediately when this code executes, it may not cause a crash until some other time in execution when that memory location becomes important, or it may cause some other strange behavior in the program. If the strcpy is changed to ''strcpy(szID, "123456")'' szID will not overflow, but szMsg will overflow in the sprintf statement that follows. 14 14 15 snprintf is a saver alternative to sprintf. snprintf has an additional parameter. The second parameter specifies the size of the buffer. The snprintf function will not exceed the specified buffer size. 16 {{{ 17 char szMsg[10]; 18 char szID[10]; 19 strcpy(szID, "123"); 20 snprintf(szMsg, sizeof(szMsg), "ID: %s", szID); 21 PrintLCD(szMsg); 22 }}} 23 24 15 25 825 applications may also be compiled using the newer C++ string type: std::string. Using std::string does not require as much diligence from the programmer. The string will automatically allocate more memory and grow if needed by an assignment. The operations are also more like the BASIC language so this is helpful for programmers who are not as skilled in C/C++. 16 26 … … 24 34 }}} 25 35 26 The 825 standard library functions now accept string parameters. We are now recommending using strings in application programs as much as possible to reduce the possibility of pointers to invalid memory, or overflow bugs.36 The 825 standard library functions now accept string parameters. We are recommending using strings in application programs where possible to reduce the possibility of pointers to invalid memory, or overflow bugs. The exception is when speed is important and frequent allocation of memory may be detrimental. For example, for a scoreboard output or computer output that will happen several times per second it may be best to use old style C character arrays. 27 37 28 38 For more information about std::strings refer to: http://www.cplusplus.com/reference/string/string/