Re: [EE] Ideas about improving safety in C language
smplx <[email protected]>
| Newsgroups | gmane.comp.hardware.microcontrollers.pic |
|---|---|
| Message-ID | <[email protected]> |
On Tue, 15 Apr 2025, Isaac Marino Bavaresco wrote: > Hi folks, > > I was thinking about the current discussion about C/C++ language safety, > and I recalled an old idea I had long ago about creating a new string > format and library. > > It could be possible for one person alone to implement and use it > privately, but of course it would be even better if it becomes a > standard, perhaps with support from the compilers. > > I don't know whether something similar was already suggested or is being > used, but I would like to know your opinion about it. > Hi Isaac, Really sorry to rain on your parade but nothing you do will ever make C/C++ strings safe. The problem is that no mater how you craft your libraries, the complier is not aware of the fundamental properties of a string so a pointer to a string will never feedback info to the compiler and the compiler will therefore never be able to compensate for pointer misuse. Consider two fundamental common operations on a string: (1) appending data to a string (2) scanning a string character by character In (1) it is often necessary to increase the size of the string. This involves allocating a new memory area on the heap (often using realloc). This sometimes causes old pointers to be invalidated - they point to sections of the heap which have been freed while the grown string has been copied to a new section of the heap. In (2) a pointer is slowly moved along a string while each character of the string is processed. Maybe a specific character is being search for. What happens if the string suddenly changes size or is moved to a new heap position? The pointer will become rouge and could cause all kinds of damage. We get the argument that a string cannot suddenly move. Actually this is a VERY real danger. What happens if two of more threads access the same string at the same time? Can't happen? What about the main line and an interrupt handler? What about a function calling another function with a string it is actualy using? The child function modifies the string, the string gets realloced and the parent function is now (sometimes) left procesing a freed section of memory. The only way you are ever going to have safe strings is if the compiler can track their use and generate extra code depending on how it sees they are being used. Just my 2 cents worth. Friendly Regards Sergio Masci