EEVblog Electronics Community Forum

Products => Computers => Programming => Topic started by: HwAoRrDk on October 27, 2022, 03:26:44 pm

Title: Should C language "undefined behaviour" cover crashing/hanging?
Post by: HwAoRrDk on October 27, 2022, 03:26:44 pm
I have been pondering this question for a few days.

After what started as an effort to write my own stripped-down, smaller printf() implementation after discovering I was nearly out of space on my MCU, I got nerd-sniped into also re-writing more efficient alternatives to my platform's C standard library 32-bit unsigned division and modulus software routines in assembly (they are used by ultoa(), which is used by my printf()). As part of testing my substitutes, I wanted to compare them to the behaviour of the standard library routines. So I wrote some test cases - some of which included dividing by zero. But to my surprise I discovered that the standard library implementation of modulus has a problem where the algorithm gets stuck in an infinite loop if the divisor is zero.

After reporting this to the maintainers, the opinion was given that it wasn't a problem, as "undefined behaviour" allows for that. I think that's a relatively cynical interpretation, and in my opinion "undefined behaviour" should - at least in this context - be that the result is undefined.

What say you lot in the peanut gallery? :)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 03:59:23 pm
It is allowed. "Result" in the context of a C spec is the state of the program, not an actual result returned by the function. So, getting stuck in a loop is a valid result as well.

Not only that, I've seen cases where GCC would replace the whole body of the function with a single instruction - UDF (architecturally undefined instruction on ARM) just because the function used an uninitialized pointer for a buffer and the rest of the code depended on that. So, the compiler eliminated all the code because as far as the spec goes, the result is the same. It could have itself replaced the whole function with a while (1);. It would have been just as valid.

In fact, I would call this behaviour desiderable in may cases. If the code gets stuck in the place where the issue is "detected", it makes it easier to debug. If the function just subtly returns the wrong result, you may have a lot of fun chasing it. Although in a more modern language, I would design in explicit checks and try to have as few undefined things as possible, ideally none. But this is not what C is, and it is to late to change.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on October 27, 2022, 04:35:44 pm
opinion "undefined behaviour" should - at least in this context - be that the result is undefined.

What say you lot in the peanut gallery? :)

Nasal demons, might jump out, throw peanuts at you from the gallery, until you make a Riemann sphere.

Edit: Ideally, it should have produced a compiler error (perhaps in an ideal world), failing that a run time error (if possible, e.g. Divide by zero error).  But really, 'undefined behavior', can do just about anything, and probably more still.  So an infinite loop, is one example, of what it can do.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: HwAoRrDk on October 27, 2022, 05:09:45 pm
See, the thing is that I totally understand the arguments that "undefined behaviour" refers to the program state. That for example, what happens when accessing beyond the end of an array is also undefined behaviour - that it may corrupt other memory and thus potentially alter the state of the program.

But what would you say when given the following scenario? What if this code will not hang the program, but give a wrong result:

Code: [Select]
a = 12345
b = 0;
c = a % b;

And this code will hang the program in an endless loop:

Code: [Select]
a = 12345
b = 0;
c = a % b;

What do you mean, "there's no difference"?

Oh, I forgot to mention the first one is using unsigned int variables, and the other unsigned long. You see, on the platform in question, the former is performed with the CPU's native division instructions, whereas the latter is performed with a software routine that has the aforementioned behaviour. The two are inconsistent with each other for what is the same arithmetic operation. I think there is some merit in things failing in a predictable way when performing the same operation.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 05:20:45 pm
I think there is some merit in things failing in a predictable way when performing the same operation.
Yes, there is, but this is not what C specification says. And compilers implement the specification. So, your complaint is to the standards people, not the compiler writers. And a lot of people have complaints to them, but they have their reasons.

All you can do is use a different language that does not have this behaviour.

If we are talking in abstract, I agree with you 100%. But when it comes to C, there is a well defined specification in place, it is fixed. You can implement "more robust" C, but it will likely break exiting software and there will be no market for it.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on October 27, 2022, 05:22:13 pm
in a more modern language, I would design in explicit checks and try to have as few undefined things as possible, ideally none. But this is not what C is, and it is to late to change.

yup, yet an other point for my-c  :D
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MarginallyStable on October 27, 2022, 06:02:52 pm
Not sure why you are trying to define "undefined behavior". It is exactly what it is.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: alm on October 27, 2022, 06:32:43 pm
Undefined behavior covers anything including the destruction of the machine (look up halt and catch fire).

If you don't want this to happen, then it's your job as C programmer to make sure you never trigger this behavior, for example by checking a divisor is non-zero before dividing. Undefined in the C spec equivalent of your doctor saying "If you get a headache after drinking five cups of coffee, then don't drink five cups of coffee".

If you want the language to take care of this instead of you, use a higher level language that defines a zero division exception or something like that.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on October 27, 2022, 07:01:47 pm
Undefined behavior covers anything including the destruction of the machine (look up halt and catch fire).

If you don't want this to happen, then it's your job as C programmer to make sure you never trigger this behavior, for example by checking a divisor is non-zero before dividing. Undefined in the C spec equivalent of your doctor saying "If you get a headache after drinking five cups of coffee, then don't drink five cups of coffee".

If you want the language to take care of this instead of you, use a higher level language that defines a zero division exception or something like that.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: HwAoRrDk on October 27, 2022, 07:08:31 pm
Yes, there is, but this is not what C specification says. And compilers implement the specification. So, your complaint is to the standards people, not the compiler writers.

I suppose you're right. I guess that's what happens when you try to mould a standard around a lot of existing and varied implementation.



Don't get me wrong, I'm not criticising the C language as a whole. If I were upset about this stuff, I wouldn't be using it. I know it's the programmer's job to avoid triggering undefined behaviour (e.g. check your divisor values first, your array bounds, that pointers are valid, etc.). I just wish in some areas (like this) there was more predictability and consistency. Speaking of which, further to my example above, I just remembered one more thing about this scenario: the routine for 32-bit division (as opposed to modulus) doesn't even have the same issue! It uses a different algorithm and is perfectly fine with a divisor of zero! Even more inconsistency. ::)

I think the whole thing about "undefined behaviour" meaning any random event could occur - up to and including your computer exploding, your hair turning purple, or being haunted by evil spirits - needs to have some kind, pragmatic consideration applied. Not for compiler or library writers to just shrug their shoulders and say "we're okay with letting random shit happen even though some of it is under our control".

Edit: That last sentence also gave rise to this thought: as I understand it, a lot of C undefined behaviour is due to having to allow for the idiosyncrasies of varied hardware. The circumstances that lead to undefined behaviour may be uncontrollable due to the nature of the platform code is running on. But when the behaviour is entirely within an entity's control (e.g. add a line of code to a library routine to perform a zero check), I think that is when pretence of "we can't help it" needs to go away.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 07:13:23 pm
needs to have some kind, pragmatic consideration applied.
This is called "defining the behaviour". Once you limit a set of outcomes, you defined the behaviour.

As a rational human being you can safely assume that your C program won't implode the universe. But you can't put that into spec.

The reason it is done this way is that they basically reserve the right to not handle corner cases, especially ones that are different between architectures. This itself limits realistically possible outcomes.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DavidAlfa on October 27, 2022, 07:27:59 pm
You can't apply rules to undefined behavior, means exactly that, might work, crash, overwrite other variables, execute random code...
You might be lucky if the CPU supports exceptions.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 07:28:52 pm
I think that is when pretence of "we can't help it" needs to go away.
"We don't check" is the defined behavior though. And this is good because it lets you write more optimal code. If you are passing some variable around, you as a programmer can check it once and then let the code assume the operation would be defined.

Again, other higher level languages do those checks, they are generating less efficient code. You pick which one you want.

This is similar to memcpy() and overlapping buffers. The function is explicit that it might break if the buffers overlap. This allows for a more efficient implementation. If you as a user can't guarantee that and don't want to check, then use memmove(). But don't make everyone else's code slower by default.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 07:35:55 pm
And as a compiler author you can define the behaviour, of course. This is not against the spec. For GCC, you have -fsanitize=integer-divide-by-zero and generally -fsanitize=undefined. The compiler would generate those checks for you. Your code would be bigger and slower as a result, but if that's what you want, then use those sanitation options.

See https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Instrumentation-Options.html for more information.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on October 27, 2022, 07:59:28 pm
"We don't check" is the defined behavior though. And this is good because it lets you write more optimal code.

If I'm allowed to produce code that doesn't give the correct output, then I can produce extremely small and performant code very quickly.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 08:03:12 pm
If I'm allowed to produce code that doesn't give the correct output, then I can produce extremely small and performant code very quickly.
Exactly. Thant's what compiler did in my case where it replaced a huge function with UDF instruction. The result of executing my huge code and this one instruction is the same, so why do more?

This only happened because undefined behavior was detected at compile-time, of course (there is probably some combination of warning flags that would have warned me, but they were not a part of -W -Wall). In run-time you just end up with a really unpredictable behavior that depends on the underlying architecture.

Compilers free to do this, so don't write code that contains UB.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on October 27, 2022, 09:26:39 pm
Hanging? How can you know that it's not actually a desired behavior in a given situation? (Hint: sometimes it is.)
How could it ever be "undefined behavior"? How could you want a loop to be undefined behavior in any situation? And how do you think "hanging" should be defined exactly?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on October 27, 2022, 09:37:45 pm
If I'm allowed to produce code that doesn't give the correct output, then I can produce extremely small and performant code very quickly.
Exactly. Thant's what compiler did in my case where it replaced a huge function with UDF instruction. The result of executing my huge code and this one instruction is the same, so why do more?

This only happened because undefined behavior was detected at compile-time, of course (there is probably some combination of warning flags that would have warned me, but they were not a part of -W -Wall). In run-time you just end up with a really unpredictable behavior that depends on the underlying architecture.

Compilers free to do this, so don't write code that contains UB.

Unfortunately there are so many subtle ways to invoke UB, and most people don't know all of them.
Or don't realise when they have invoked UB.
Or don't realise when the library they are using invokes UB internally.
Or don't realise when their use of a library invokes UB.
Or don't realise that an upgraded compiler now detects and makes use of UB.

Basically UB is fragile.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: ataradov on October 27, 2022, 09:43:11 pm
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it. And I can't blame standard maintainers for not wanting to break things. It is better that way. Look at Python developers, they are happily breaking things all the time to male it "better".

C is what it is. Although I personally don't like most of the new languages, there are good arguments for not using C anymore, especially for really critical stuff.

I would like to se improved version of C, but unfortunately all attempts at this instantly grow a ton of features and become bloated and unusable.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on October 27, 2022, 10:08:28 pm
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it. And I can't blame standard maintainers for not wanting to break things. It is better that way. Look at Python developers, they are happily breaking things all the time to male it "better".

C is what it is. Although I personally don't like most of the new languages, there are good arguments for not using C anymore, especially for really critical stuff.

I would like to se improved version of C, but unfortunately all attempts at this instantly grow a ton of features and become bloated and unusable.

Agreed. (How boring!)

Except C is no longer a svelte lean language - "bloated" and "unusable" do apply to C. (C++ is even worse)

Multicore CPUs are forcing the adoption of new languages, and about time too :)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on October 27, 2022, 10:46:40 pm
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it. And I can't blame standard maintainers for not wanting to break things. It is better that way. Look at Python developers, they are happily breaking things all the time to male it "better".

C is what it is. Although I personally don't like most of the new languages, there are good arguments for not using C anymore, especially for really critical stuff.

I would like to se improved version of C, but unfortunately all attempts at this instantly grow a ton of features and become bloated and unusable.

don't blame? I do!
C sucks and can be fixed, just people don't do it without putting too much Ego burst into it!

People can blather things over and over in endless discussions.
I have already fixed the UB problem once and forever: my-C is *THE* solution for me.

It's no C++, it's not C with classes, it's 90% compatible with MISRA C & DO178{B,C} level {A, B}, and it doesn't have UB because it enforces monads.

Monads are *THE* key. Sure they look quirk, and the machine layer generates less efficient machine code (due to the nature of monads), but the language is more coherent and, better still, the generated code is more robust at run time.


Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on October 27, 2022, 10:53:34 pm
When there is no good reason, don't cause unrecoverable program failure for unexpected input. It crashes rockets.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on October 27, 2022, 11:01:10 pm
Multicore CPUs are forcing the adoption of new languages, and about time too :)

The reason why I developed my-C is ... because there is no C compiler for R18200, a MIPS5 superscalar multicore prototype with tr-memory.

for complex projects like ... a filesystem, on a superscalar + out of order + Tr-memory architecture is something for which you can't have UBs if you want to write something working without spending your entire life on the debugger  :o :o :o

Seriously? I wonder how guys at IBM can collaborate with guys at GNU Gcc and guys at LINUX-dev to support POWER9 and POWER10 cores and their tr-memory  :o :o :o

The Linux kernel is still written in standard C, thus respect for those guys! They must be super-gurus!
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on October 27, 2022, 11:12:46 pm
When there is no good reason, don't cause unrecoverable program failure for unexpected input. It crashes rockets.

I remember an ARING unit on a supersonic airplane: if you unplug the serial RS422 cable of the MTC bridge (or if something cuts the cable) ... ops, unexpected input, machine exception raised, and you see the whole MTC crashing.

Pray this doesn't happen when you fly faster than sound waves!
Pray this doesn't happen when you flying in the enemy area!

MTC means "mission tactical computer", it's super redundant, but since there are no monads behind the datatypes in the ISRs, well ... unplugging the cable is really something unexpected, not handled by anything, which, worse still is then subjected to undefined behavior.

That's why DO178B-levelA says you have to remove all the dead-code and adds extra care during the software testing activities.

What if the undefined behavior arm and shoot a missile? or eject the pilot?

(ok, here there are extra protections, but you get the point)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on October 27, 2022, 11:15:57 pm
the serial RS422 cable of the MTC bridge

To make you laugh: that cable is the logger cable.
So, you unplug the data logger, you crash the MTC.

Nice feature, ain't it  ;D ?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 03, 2022, 07:52:50 pm
Yes, there is, but this is not what C specification says. And compilers implement the specification. So, your complaint is to the standards people, not the compiler writers.

I suppose you're right. I guess that's what happens when you try to mould a standard around a lot of existing and varied implementation.



Don't get me wrong, I'm not criticising the C language as a whole. If I were upset about this stuff, I wouldn't be using it. I know it's the programmer's job to avoid triggering undefined behaviour (e.g. check your divisor values first, your array bounds, that pointers are valid, etc.). I just wish in some areas (like this) there was more predictability and consistency. Speaking of which, further to my example above, I just remembered one more thing about this scenario: the routine for 32-bit division (as opposed to modulus) doesn't even have the same issue! It uses a different algorithm and is perfectly fine with a divisor of zero! Even more inconsistency. ::)

I think the whole thing about "undefined behaviour" meaning any random event could occur - up to and including your computer exploding, your hair turning purple, or being haunted by evil spirits - needs to have some kind, pragmatic consideration applied. Not for compiler or library writers to just shrug their shoulders and say "we're okay with letting random shit happen even though some of it is under our control".

Edit: That last sentence also gave rise to this thought: as I understand it, a lot of C undefined behaviour is due to having to allow for the idiosyncrasies of varied hardware. The circumstances that lead to undefined behaviour may be uncontrollable due to the nature of the platform code is running on. But when the behaviour is entirely within an entity's control (e.g. add a line of code to a library routine to perform a zero check), I think that is when pretence of "we can't help it" needs to go away.

Well it is undefined, their docs make that clear. One could argue - hypothetically - that division by zero is a known no-no, so what is it in the algorithms of the system that cause the denominator to get set to zero? get into an invalid state? If the software is deterministic then the invalid state must be seen as a bug of some kind with some explanation, somewhere there is an assignment to memory that sets that number to zero or it is uninitialized.

Of course with exception support life is a lot easier.


 
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: cfbsoftware on December 05, 2022, 11:19:05 pm
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it.
I can blame them. The relevant knowledge was available at that time.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: hamster_nz on December 06, 2022, 04:36:03 am
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it.
I can blame them. The relevant knowledge was available at that time.
I am sure they did think about it. Hardware back then was far less 'generic' in capability and implementation. Even how many bits were in a character or byte was still up in the air. This is over a decade before IEEE floating point was a thing.

C was designed around what is the minimum reasonable behavior we can expect from a computer. C also says "don't play outside that safe space if you want consistent, portable, predictable results from your code".
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 06, 2022, 08:50:05 pm
I fully agree. And I don't like that UB exists. But I can hardly blame people in 1972 for not thinking about it.
I can blame them. The relevant knowledge was available at that time.
I am sure they did think about it. Hardware back then was far less 'generic' in capability and implementation. Even how many bits were in a character or byte was still up in the air. This is over a decade before IEEE floating point was a thing.

C was designed around what is the minimum reasonable behavior we can expect from a computer. C also says "don't play outside that safe space if you want consistent, portable, predictable results from your code".
Yes, yes and yes.
No UB almost always guarantees more overhead for the compiled code, and/or stringent constraints on the supported targets. Neither is a fit for C.
I will even venture that had C not had any UB cases, it would have been long dead by now.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 09:11:32 am
I will even venture that had C not had any UB cases, it would have been long dead by now.
Yes - C is practical, like many of us engineers. And I truly enjoy seeing how the practicality of C and the massive success thereof triggers so many "computer scientist" types of people who can't stand something so practical just works against their expectations, and refuses to die or get replaced against their predictions, decade after decade. I'm not as much as C fanboy, but more like a "C hatred discussion enjoyer".
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 07, 2022, 10:14:50 am
I will even venture that had C not had any UB cases, it would have been long dead by now.
Yes - C is practical, like many of us engineers. And I truly enjoy seeing how the practicality of C and the massive success thereof triggers so many "computer scientist" types of people who can't stand something so practical just works against their expectations, and refuses to die or get replaced against their predictions, decade after decade. I'm not as much as C fanboy, but more like a "C hatred discussion enjoyer".

As a practicing electronics and software engineer, I too like practical tools and products.

One principal characteristic of a practical tool is that it is predictable and without surprises. Those characteristics are the principal reason HP became a great instrumentation company: their products just worked as you would expect them to work. "Nobody was ever fired for buying HP"

K&R C satisfied those characteristics. OK, you had to read both books about C, but together they were about 2cm thick.

Modern C fails to have those characteristics. That's due to the increased complexity of the underlying hardware, and C's attempts to be both "low-level-close-to-Si" and "general-high-level-applications" languages.

My preference would be for C to be only low-level close-to-the-silicon, and to have left applications to other languages. In any case, the community is voting against C for the latter in favour of Java, Rust, and other simpler and more practical (for general purpose applications) languages.

So, in trying to be all things to all people, C stopped being ideal for its important niche.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 10:19:04 am
nobody mentioned the fix/workaround? C++ Exceptions try and catch (https://www.w3schools.com/cpp/cpp_exceptions.asp)? well ok, its C++, we only want C right?... so <errno.h> (https://data-flair.training/blogs/error-handling-in-c/) well, still not quite it... then why you dont build your own "C Library" (the stripped down one if you like) with whatever your heart content behaviour you like once the "undefined behaviour" is encountered? or why you are not capable of doing a rigorous unit testing?

btw imho, entering a infinite loop after an undefined behaviour is an ill behaviour, even though specification approved it. imagine a rocket launched that relies on the software for trajectory calculation, with undetected bug before the launch.. what happen when the software goes infinite loop? it will just do nothing except wasting mcu energy doing infinite loop. and what chance the rocket can survive or recover when the software halted? if program continues (ignores) after an undefined is triggered, at least there is non-zero chance that it will recover (by luck), or by itself or the nature of the code that will reset all values once new sensors data are retreived...


(https://scontent.fkul4-3.fna.fbcdn.net/v/t1.6435-9/106695097_2614292882117941_8905660811076373624_n.jpg?_nc_cat=106&ccb=1-7&_nc_sid=730e14&_nc_ohc=1MayOPXVxioAX-pJPJD&_nc_ht=scontent.fkul4-3.fna&oh=00_AfBvH-5ogUYFCevz6o7sf5MPnjNEqYG29RdFhXu3ocG2tA&oe=63B7D359https://scontent.fkul4-3.fna.fbcdn.net/v/t1.6435-9/106695097_2614292882117941_8905660811076373624_n.jpg?_nc_cat=106&ccb=1-7&_nc_sid=730e14&_nc_ohc=1MayOPXVxioAX-pJPJD&_nc_ht=scontent.fkul4-3.fna&oh=00_AfBvH-5ogUYFCevz6o7sf5MPnjNEqYG29RdFhXu3ocG2tA&oe=63B7D359)


imho undefined behaviour should provide exit or re entry/reboot vector to the software, at the very least basic level is C++ style catch all exceptions, if its too hard to do, your custom library should callback to one generic function act as exception handler for all... or you analyze for any possible singularities, or better, do rigorous unit testing. if you dont know how to do that given any language thrown at you, or the one you choosed, please dont accept a tender offer relating to life critical project, if you dont have senior and experienced colleague programmer that has very clear solution in mind about how to take care of that... you may just want to generate your code from Google AI.

or, repeating this (to back me up?)...
Undefined behavior covers anything including the destruction of the machine (look up halt and catch fire).

If you don't want this to happen, then it's your job as C programmer to make sure you never trigger this behavior, for example by checking a divisor is non-zero before dividing. Undefined in the C spec equivalent of your doctor saying "If you get a headache after drinking five cups of coffee, then don't drink five cups of coffee".

If you want the language to take care of this instead of you, use a higher level language that defines a zero division exception or something like that.
i wish i can type more but this new SMF forum "quoting system" is f*king annoying. a proof that newer program is not always better, given a "not so thoughtfull" person behind programming it.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 11:42:21 am
As I and many others have said before, the C language was never really designed, certainly not in the formal manner we expect to see when an amplifier is designed or a jet engine or radio receiver. So its silly to expect it to behave like it was designed, if you want predictable behavior under unanticipated circumstances, then I'm sorry but that requires work, effort, creativity AKA design, and C ain't it.

C was a hack job, a quick and dirty "it'll do for now" because designing was too much effort, it wasn't intended to be a serious, practical language, just something crude but useable to play with operating system ideas.

It became popular while still little more than a prototype, a proof of concept, and once inertia got behind it any prospect of real design or a serious review and restatement of goals became impossible.

There could have been a C version 2.0 project that tidied up loose ends, incorporated exception handling, improved the grammar and so on, that could have been willing to break backward compatibility in order to do things right. But it never happened and to this day many developers wax lyrical, expressing affection for what is a kludge.

C is very valuable because we can learn from it, mistakes are hugely valuable for this reason, one must make mistakes to make true progress, but valuing mistakes doesn't mean we should wallow in them, admire them and defend them.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 07, 2022, 11:50:43 am
Old IBM mainframe mime, look up halt and catch fire.
Today is "disable channels.and halt".
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 11:59:05 am
C was a hack job, a quick and dirty "it'll do for now" because designing was too much effort, it wasn't intended to be a serious, practical language, just something crude but useable to play with operating system ideas.
says who? says someone who collecting questionaires about machine and ARM language in this forum in this few days? or says someone better than Bell's Lab computer scientist who got a Turing Award? working for years on it? and Unix, from where Linux was originated? https://en.wikipedia.org/wiki/C_(programming_language)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 12:08:39 pm
C was a hack job, a quick and dirty "it'll do for now" because designing was too much effort, it wasn't intended to be a serious, practical language, just something crude but useable to play with operating system ideas.
says who? says someone who collecting questionaires about machine and ARM language in this forum in this few days? or says someone better than Bell's Lab computer scientist who got a Turing Award? working for years on it? and Unix, from where Linux was originated? https://en.wikipedia.org/wiki/C_(programming_language)

Don't rant about me the person, prove me wrong, if you have evidence I'm wrong then present it and we can discuss the matter without animosity or insults or insinuations of incompetence.

Trying to argue against me on the basis of presumed credentials or lack thereof won't strengthen your case, besides I've designed and developed compilers far more sophisticated than C, have you? still want to talk credentials?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 12:15:42 pm
C was a hack job, a quick and dirty "it'll do for now" because designing was too much effort, it wasn't intended to be a serious, practical language, just something crude but useable to play with operating system ideas.
says who? says someone who collecting questionaires about machine and ARM language in this forum in this few days? or says someone better than Bell's Lab computer scientist who got a Turing Award? working for years on it? and Unix, from where Linux was originated? https://en.wikipedia.org/wiki/C_(programming_language)

Don't rant about me the person, prove me wrong, if you have evidence I'm wrong then present it and we can discuss the matter without animosity or insults or insinuations of incompetence.

Trying to argue against me on the basis of presumed credentials or lack thereof won't strengthen your case, besides I've designed and developed compilers far more sophisticated than C, have you? still want to talk credentials?
did you click and read the link? and the links inside? where is your credentials or proofs? you can talk to yourself that when you make a wild statement, please also provide your proofs to show you are right.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 12:23:39 pm
As regards the title/topic of this thread.  The point is, C is suppose to be (as I understand it), a systems language.

Consider, a hypothetical Make Character Uppercase, type of function.  Which might boil down to just being a logical OR or AND, of the appropriate byte, with the correct binary immediate value, to accomplish the task.

If you do it with a single OR or AND instruction (as necessary, depending on if UPPER or LOWER case needed, etc).  It can perhaps take 1/7th of an instruction cycle to execute (assuming typically 7 instructions are executed in the same cycle, by the superscaler processor and its out of order unit).

But, if it is insisted that the language performs extensive safety checks, at run time, even at the lowest (system) level.  It might need to check the address is within the valid bounds of the particular array (if applicable).  It might check the value is NOT 0 (NULL), as that may indicate a possible error somewhere.
It could check the value is not less than 32, and is not too big, etc.
Possibly other safety checks could be implemented.

But then with all the extra memory accesses, comparisons, branches and other stuff.  It might take 5 or even 20 or more times longer to execute.

So, if all those safety checks are applied to nearly all operations, even at such a fundamentally low level.  The language will end up producing stuff, which takes, perhaps twenty times longer to run, compared to if it could just ignore all those safety checks.

So, if GCC (mostly written in C) takes 10 minutes, to currently compile all your files, for a particular project, it would then end up taking, perhaps 200 minutes, instead (assuming the GCC time, was mostly due to CPU performance).

Similarly, most other things (which end up being written in C), would also take (perhaps) twenty times longer.

Such a situation, would tend to reduce peoples interest in C, and maybe make another language, be rather popular, because of its execution speed.

Some of the safety checks (in general), could be done at compile time, without affecting run time performance.  In which case, they could be useful, as long as the compile times, don't end up becoming too long, as a result.

In other words, in practice.  It is often necessary to choose between a very safe/robust language, that tends to protect users and programmers, against some kinds of mistakes/errors, but is perhaps not the fastest of languages, and language(s), that give the ultimate performance, that a computer can give.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: mfro on December 07, 2022, 12:37:32 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 12:38:05 pm
C was a hack job, a quick and dirty "it'll do for now" because designing was too much effort, it wasn't intended to be a serious, practical language, just something crude but useable to play with operating system ideas.
says who? says someone who collecting questionaires about machine and ARM language in this forum in this few days? or says someone better than Bell's Lab computer scientist who got a Turing Award? working for years on it? and Unix, from where Linux was originated? https://en.wikipedia.org/wiki/C_(programming_language)

Don't rant about me the person, prove me wrong, if you have evidence I'm wrong then present it and we can discuss the matter without animosity or insults or insinuations of incompetence.

Trying to argue against me on the basis of presumed credentials or lack thereof won't strengthen your case, besides I've designed and developed compilers far more sophisticated than C, have you? still want to talk credentials?
did you click and read the link? and the links inside? where is your credentials or proofs? you can talk to yourself that when you make a wild statement, please also provide your proofs to show you are right.

I'm very familiar with C and that Wikipedia article, why did you want me to look at it? But, consider this, from that article:

Quote
Thompson desired a programming language to make utilities for the new platform. At first, he tried to make a Fortran compiler, but soon gave up the idea.

These guys borrowed a few ideas from PL/I like pointers, include files, preprocessing (which they did very poorly in C), but they didn't have the compiler design experience to build a PL/I compiler or even a Fortran compiler. There's nothing wrong with that, with what they did, but they did not aspire to exploit some of the latest ideas in programming language design.

They ignored exception handling, superbly supported (in fact first introduced) in PL/I, the gave up on the preprocessor, again an idea that was at the time at its pinnacle in PL/I (do some reading on PL/I's preprocessor!). They abandoned strings and bit data types.

Writing an OS and having no exception handling support in the language is not an encouraging design decision, a divide by zero or something, in kernel mode code, could crash the OS. The Multics team fully appreciated that and is why they adopted PL/I, the first language to support exceptions (called "conditions" in PL/I parlance).

Remember exceptions is an inherent characteristic of CPUs, its a "hardware feature" so if C was "designed to be close to the hardware" it would have incorporated exception handling wouldn't it?

So if C had been truly designed, let alone designed for writing an OS, it would not have ignored these recent cutting edge programming language ideas.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 01:00:51 pm
if you call evolution, improvement, expansion is a hack, then everything is a hack including python and what you are going to (re) invent... C evolved, you dont expect whats work today will work 10-20 years from now. and its not the first language Ritchie experimented. please know your place... unless if you already have something better (credentials) to prove, ie once your language got on top list for decades....

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.
yes use C sharp (C#)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 01:14:11 pm
if you call evolution, improvement, expansion is a hack, then everything is a hack including python and what you are going to (re) invent... C evolved, you dont expect whats work today will work 10-20 years from now. and its not the first language Ritchie experimented. please know your place... unless if you already have something better (credentials) to prove, ie once your language got on top list for decades....

Yes "hack" is normal when being creative, I agree with you. But creativity is also about the human mind imposing order and consistency and symmetry on things, so its cyclic, hack/review, hack/review, good design doesn't stop at the hack stage, but at the review and reorganization following lessons learned etc.

I'm also not arguing that C is not ubiquitous (I avoid describing it as "popular"). It is ubiquitous, that's not automatically a good thing either, guns are ubiquitous in the US, nothing good about that.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 07, 2022, 01:22:43 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 01:36:18 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.

That's interesting, such subtleties are often far from obvious. I made a PL/I compiler crash in the past, in PL/I you can declare a variable as "based on" some pointer. That it, the pointer used to get at the variable is stated in the declaration, in the code just access the variable by name, without explicit use of a pointer.

Anyway, these declarations can crash some compilers:

Code: [Select]

dcl a_ptr pointer based (b_ptr);
dcl b_ptr pointer based (a_ptr);


I "fixed" this in my own compiler by counting how many steps are taken during the resolution of a variable's address, if it's > 100 say, we stop and report a recursively declared variable, it did the trick (I admit this was a true "hack") and its pretty unlikely real code would ever chain declarations to that degree.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 01:42:27 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.

If you cover the scalpel, with cotton wool, safety tape and other precautions, making it so that even a toddler, could use it safely.

What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

If a tricky embedded system, needs to perform a very rapid software operation, in order to work, safely and correctly, otherwise, the voltage/system/etc will change too much (in real-time), ruining the motor controller, or whatever the system/software is trying to do.

Then your suggested 'new' language, i.e. NOT very high speed/efficient C, may make the task relatively unsolvable with the existing/affordable hardware.

In other words.  Use the RIGHT TOOL for the RIGHT JOB.  Not some film-flamcy cotton wool, safety tape covered, thing, that is not suitable for doing the job in hand.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 02:46:51 pm
What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

If a tricky embedded system, needs to perform a very rapid software operation, in order to work, safely and correctly, otherwise, the voltage/system/etc will change too much (in real-time), ruining the motor controller, or whatever the system/software is trying to do.

Then your suggested 'new' language, i.e. NOT very high speed/efficient C, may make the task relatively unsolvable with the existing/affordable hardware.

In other words.  Use the RIGHT TOOL for the RIGHT JOB.  Not some film-flamcy cotton wool, safety tape covered, thing, that is not suitable for doing the job in hand.

To be fair, C has some footguns, uncertainties and unsafety that are not required to get the power. It is just that people who find C unusably bad, tend to come up with much worse alternatives that fail to provide the "power" as you point out.

C is like a scalpel which fits in the hand relatively well, but not perfectly, and sometimes it slips. Most "C hateboys" are those who ask for a language where scalpel is wrapped in cotton wool, or a scalpel that looks like a beautiful cathedral. But the right thing to ask for is a scalpel which is still a scalpel, but a few safety improvements. Think about a knife with that "bump" in the handle which prevents your hand from slipping into the blade if you push it down. C lacks this "bump". But C has a rigid screw hole in the right place so you can easily add this bump.

I do admit it is interesting to discuss about the crappiness of C, but the end result seems to be: it's still not colossally too bad, and alternatives do not prove very usable, so - we stick with C, and we are careful, and we make far fewer mistakes than the "C is dangerous" alarmists claim. At least for myself, 95% of my bugs are in logical thinking and would happen in any language. Maybe some 5% would be avoidable with a better designed language. I don't even remember when I last time overindexed a table or made a mistake with a zero-terminated string, it has been years!
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 03:01:30 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.

If you cover the scalpel, with cotton wool, safety tape and other precautions, making it so that even a toddler, could use it safely.

What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

If a tricky embedded system, needs to perform a very rapid software operation, in order to work, safely and correctly, otherwise, the voltage/system/etc will change too much (in real-time), ruining the motor controller, or whatever the system/software is trying to do.

Then your suggested 'new' language, i.e. NOT very high speed/efficient C, may make the task relatively unsolvable with the existing/affordable hardware.

In other words.  Use the RIGHT TOOL for the RIGHT JOB.  Not some film-flamcy cotton wool, safety tape covered, thing, that is not suitable for doing the job in hand.

The danger with analogies is that even a slightly misleading one can lead to conclusions that aren't true for the original scenario. We can compare C to a broken chainsaw, or a broken semi automatic, nobody would advocate a surgeon use a broken scalpel, or a scalpel with a chipped, loose, blunt blade would they?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 03:08:54 pm
What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

If a tricky embedded system, needs to perform a very rapid software operation, in order to work, safely and correctly, otherwise, the voltage/system/etc will change too much (in real-time), ruining the motor controller, or whatever the system/software is trying to do.

Then your suggested 'new' language, i.e. NOT very high speed/efficient C, may make the task relatively unsolvable with the existing/affordable hardware.

In other words.  Use the RIGHT TOOL for the RIGHT JOB.  Not some film-flamcy cotton wool, safety tape covered, thing, that is not suitable for doing the job in hand.

To be fair, C has some footguns, uncertainties and unsafety that are not required to get the power. It is just that people who find C unusably bad, tend to come up with much worse alternatives that fail to provide the "power" as you point out.

C is like a scalpel which fits in the hand relatively well, but not perfectly, and sometimes it slips. Most "C hateboys" are those who ask for a language where scalpel is wrapped in cotton wool, or a scalpel that looks like a beautiful cathedral. But the right thing to ask for is a scalpel which is still a scalpel, but a few safety improvements. Think about a knife with that "bump" in the handle which prevents your hand from slipping into the blade if you push it down. C lacks this "bump". But C has a rigid screw hole in the right place so you can easily add this bump.

I do admit it is interesting to discuss about the crappiness of C, but the end result seems to be: it's still not colossally too bad, and alternatives do not prove very usable, so - we stick with C, and we are careful, and we make far fewer mistakes than the "C is dangerous" alarmists claim. At least for myself, 95% of my bugs are in logical thinking and would happen in any language. Maybe some 5% would be avoidable with a better designed language. I don't even remember when I last time overindexed a table or made a mistake with a zero-terminated string, it has been years!

Well I can argue that the committed C devotees, can only ever defend their position by making up analogies! Defending the language on technical, engineering, computational prowess or expressive merits is just too hard to do.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on December 07, 2022, 03:10:00 pm
What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

I think it's more like tablesaws with saw stops and without, lots of professional wood workers will keep becoming 9 digit professionals for the foreseeable future but times are a changing.

C programmers got their chance with Cyclone C, now bean counters will make the choice and it will not be C-like. Learn to love Rust and Ada-SPARK, though I admit they are hard to love.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 03:59:34 pm
I think it's more like tablesaws with saw stops and without, lots of professional wood workers will keep becoming 9 digit professionals for the foreseeable future but times are a changing.

C programmers got their chance with Cyclone C, now bean counters will make the choice and it will not be C-like. Learn to love Rust and Ada-SPARK, though I admit they are hard to love.

That's a good counter analogy.  As CPUs become ever increasingly fast, powerful and relatively low cost (for the performance you get).  The importance of compiler language's speed efficiency, gradually diminish, over the years.

I'd prefer if a particular language, had programmer adjustable options, which could vary the amount of safety checking, a compiler does, especially during run-time.  Then during some parts of code production and/or testing/debugging, a high safety checking mode/status could be selected.
But for eventual production releases (non-safety-critical ones), those various safety checks could be disabled.
But if it was especially important and/or safety-critical and/or doesn't need high efficiency compilation.  The safety checks could be left enabled.

Some languages, already include such features, such as Lazarus/FreePascal, Borland (various name changes, later) Pascal/Delphi, and so on.  With things like forced array bounds checking and overflow, checks being enabled or disabled, at will, inside the compiler/linker configurations.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 04:07:34 pm
Well I can argue that the committed C devotees, can only ever defend their position by making up analogies! Defending the language on technical, engineering, computational prowess or expressive merits is just too hard to do.

You miss the fact that we do engineering, based on technical facts, day in day out. These discussions are free-time for us, and making up analogies is fun.

Also the technical sides have been pretty much covered already, over and over again.

Besides, whenever we go deep into technical, factual reasoning, nothing seems to be enough for you because you want "proof" instead of "opinions". So enjoy actual opinions, and some stupid analogies. It's more fun, anyway.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 04:13:09 pm
I'd prefer if a particular language, had programmer adjustable options, which could vary the amount of safety checking, a compiler does, especially during run-time.

Many of the things people want from C, are actually available as compiler extensions already, and as a practicalist, that is completely fine to me, and I don't feel bad still calling it "C". GCC can add runtime checks for out of bound array access, and also check UB, as ataradov already showed on post #13: https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Instrumentation-Options.html

But these threads always go in circles because people enjoy the discussion itself and do not spend a lot of time in reading and digesting what was said and what the consequences are thereof.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 04:19:44 pm
To be fair, C has some footguns, uncertainties and unsafety that are not required to get the power. It is just that people who find C unusably bad, tend to come up with much worse alternatives that fail to provide the "power" as you point out.

C is like a scalpel which fits in the hand relatively well, but not perfectly, and sometimes it slips. Most "C hateboys" are those who ask for a language where scalpel is wrapped in cotton wool, or a scalpel that looks like a beautiful cathedral. But the right thing to ask for is a scalpel which is still a scalpel, but a few safety improvements. Think about a knife with that "bump" in the handle which prevents your hand from slipping into the blade if you push it down. C lacks this "bump". But C has a rigid screw hole in the right place so you can easily add this bump.

I do admit it is interesting to discuss about the crappiness of C, but the end result seems to be: it's still not colossally too bad, and alternatives do not prove very usable, so - we stick with C, and we are careful, and we make far fewer mistakes than the "C is dangerous" alarmists claim. At least for myself, 95% of my bugs are in logical thinking and would happen in any language. Maybe some 5% would be avoidable with a better designed language. I don't even remember when I last time overindexed a table or made a mistake with a zero-terminated string, it has been years!

I think a significant part of the C languages success, has been that it has reached a sort of 'critical mass'.  It has sort of become one of the main languages, for a number of reasons:


In some respects, it (C) is a bit like Windows.  People use it (critical mass), because it has become so common-place and well used, that to NOT use it, would be a major headache, and potentially badly affect future sales of a software product.

I.e. The item in question (E.g. Windows), is NOT necessarily that good/brilliant, these days.  But has become so common-place, that, that fact alone, is enough to sort of force it on people.

E.g. I'm not necessarily a big fan of windows, and perhaps try to avoid it.  But some things, such as some particular types of software and/or hardware.  Can be difficult or very tricky to use, without using windows.
Such as a new FPGA kit, which ONLY comes with windows drivers to write to the FPGA development board, and its development software, ONLY runs on windows, and can't be made to run on a windows emulated environment (wine), in Linux.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 04:22:56 pm
Well I can argue that the committed C devotees, can only ever defend their position by making up analogies! Defending the language on technical, engineering, computational prowess or expressive merits is just too hard to do.

You miss the fact that we do engineering, based on technical facts, day in day out. These discussions are free-time for us, and making up analogies is fun.

Also the technical sides have been pretty much covered already, over and over again.

Besides, whenever we go deep into technical, factual reasoning, nothing seems to be enough for you because you want "proof" instead of "opinions". So enjoy actual opinions, and some stupid analogies. It's more fun, anyway.

Alright, that's fine with me, analogies it is! So if the C language was implemented in hardware, it would look a lot like this:

(https://i.pinimg.com/736x/55/89/2b/55892bc762fbce02facbdd6107cddeea.jpg)

You can see all of the many vendor extensions there quite well, the support of different standards here and there too, pretty much captures all of the bells and whistles I think.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 04:28:41 pm
The danger with analogies is that even a slightly misleading one can lead to conclusions that aren't true for the original scenario. We can compare C to a broken chainsaw, or a broken semi automatic, nobody would advocate a surgeon use a broken scalpel, or a scalpel with a chipped, loose, blunt blade would they?

That is true.  But powerful analogies and metaphors, can be useful techniques, for rapidly getting points across, to many people, reasonably quickly.

Fire, fire, get the heck out of here, else get burnt to a crisp.

Gets to the point much quicker, than saying something like:

I hope you don't mind me pointing this out.  But there is a tiny little bit of smouldering going on here.  Which in time, might get worse. Etc ...................

The low level features of C, are sort of like, having a mini-assembly like language, built into C.  So, the potential dangers, of such features.  Are arguably no worse, than real assembly language.  Which will usually blindly do whatever you ask of it, however crazy/mistaken the program accidentally/unintentionally becomes.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 04:37:07 pm
(https://i.pinimg.com/736x/55/89/2b/55892bc762fbce02facbdd6107cddeea.jpg)

No, I think you accidentally posted C++ (just the standard without compiler extensions).

C with compiler extensions is attached.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 04:51:32 pm
(https://i.pinimg.com/736x/55/89/2b/55892bc762fbce02facbdd6107cddeea.jpg)

No, I think you accidentally posted C++ (just the standard without compiler extensions).

C with compiler extensions is attached.

Ahh, you're right, my apologies, here we go, if the C language was clothing:

(http://lh6.ggpht.com/__hNkdGikmfU/S1b4rmDB9PI/AAAAAAAAASs/wd2dTgBd2GE/s400/caduta-009392-2_-3__tonemapped.JPG)

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 04:59:57 pm
Alright, that's fine with me, analogies it is! So if the C language was implemented in hardware, it would look a lot like this:

(https://i.pinimg.com/736x/55/89/2b/55892bc762fbce02facbdd6107cddeea.jpg)

You can see all of the many vendor extensions there quite well, the support of different standards here and there too, pretty much captures all of the bells and whistles I think.
i dont get your analogy... what different vendor extensions? what different standards? and what are you suggesting as better alternative? i will looking forward to look up vendor extensions and different standards on the better language you are suggesting.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 05:04:45 pm
Many of the things people want from C, are actually available as compiler extensions already, and as a practicalist, that is completely fine to me, and I don't feel bad still calling it "C". GCC can add runtime checks for out of bound array access, and also check UB, as ataradov already showed on post #13: https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Instrumentation-Options.html

But these threads always go in circles because people enjoy the discussion itself and do not spend a lot of time in reading and digesting what was said and what the consequences are thereof.

I see.  I hadn't notice (or had forgotten) that post you refer to (#13).  Thanks, that is a GOOD post, to know about!

Those flag settings, look useful in some circumstances.  Some of those options (not the ones you mentioned), are only available on some architectures and/or can't work in combination with some other flag settings.

Those 'going round in circles', is perhaps partly because we don't (yet at least), have a post scoring mechanism and/or post highlighting and/or best/voted/favorite post, moved to top and highlighted, feature.  In the forum software.  But Dave seemed to mention/ask about it recently.

The downside of course, would be that it would annoy some people, whose post(s) didn't get chosen/upvoted and the timeline of thread/post development, would be lost and potentially more confusing than it is, now.

Also, sometimes the favorite post chosen by the OP, is the one they like, but is NOT the technically best/correct answer really.  Just the one, that apparently agrees, with the OPs, pre-existing technical misunderstandings.

E.g. An expert recommends only changing the fuse to an equivalent/identical one, of no higher current rating.
Whereas the chosen by OP as best answer post, is by some random person, who basically described using a nail as a short-circuit device.  Just because it is much cheaper, easier, and doesn't involve buying the correct fiddly fuse(s).
Despite the answer being somewhat crazy, potentially highly dangerous, and unsafe advise.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 05:21:28 pm
Ahh, you're right, my apologies, here we go, if the C language was clothing:

(http://lh6.ggpht.com/__hNkdGikmfU/S1b4rmDB9PI/AAAAAAAAASs/wd2dTgBd2GE/s400/caduta-009392-2_-3__tonemapped.JPG)

Isn't that the opposite? I mean, C lets you do pretty much what you want, including unsafe things. The clothing pictured would be when a C greybeard becomes mentally unstable and is given Ada to work with to do less harm, no?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 05:22:16 pm
Those 'going round in circles'
i think because one group want everything if possible readily served on silver plater, ie the built-in library, the compiler, and the (managed) language is doing the job for them, the boundary check, UB's behaviour etc. i guess thats what the profession demands for production's sake. this goes me extrapolating that what they actually wish for is a language/compiler that can read their mind or at least program a simple line DoMyProgram() and everything is done. and the other old school group (probably for hobby sake like me) still want to stick with all manual control bare down to the metal language who happily do if ((i >= size) || (divisor == 0)) CallBackUndefineBehaviour(); or diy build a bulletproof memory management class/library for a particular resource limited HW, i think this is what OP tried to do and solve halfly and then encountered problem in built-in/standard library, which library vendor/maker? i'm not sure but i dont recall an infinite loop on my M$ C/C++ compiler during my entire life programming, it just throw exception and program exited. lets hope we extinct and lets see what the new generation/language can offer in the future, better or worse? without C... Google AI possibly that is...
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 05:23:12 pm
Alright, that's fine with me, analogies it is! So if the C language was implemented in hardware, it would look a lot like this:

(https://i.pinimg.com/736x/55/89/2b/55892bc762fbce02facbdd6107cddeea.jpg)

You can see all of the many vendor extensions there quite well, the support of different standards here and there too, pretty much captures all of the bells and whistles I think.
i dont get your analogy... what different vendor extensions? what different standards? and what are you suggesting as better alternative? i will looking forward to look up vendor extensions and different standards on the better language you are suggesting.

Arm C Language Extensions (http://file:///C:/Users/Hugh/Downloads/acle-2021Q2.pdf)

Microsoft extensions to C (https://learn.microsoft.com/en-us/cpp/build/reference/microsoft-extensions-to-c-and-cpp?view=msvc-170)

Nvidia C Language extensions (https://developer.download.nvidia.com/compute/DevZone/docs/html/C/doc/CUDA_C_Programming_Guide.pdf)

Microchip C Language extensions (https://www.puntoflotante.net/51288f.pdf)

Ahh, the old "what are you suggesting as better alternative" defense, how predictable.











Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 05:26:40 pm
Ahh, you're right, my apologies, here we go, if the C language was clothing:

(http://lh6.ggpht.com/__hNkdGikmfU/S1b4rmDB9PI/AAAAAAAAASs/wd2dTgBd2GE/s400/caduta-009392-2_-3__tonemapped.JPG)

Isn't that the opposite? I mean, C lets you do pretty much what you want, including unsafe things. The clothing pictured would be when a C greybeard becomes mentally unstable and is given Ada to work with to do less harm, no?

Well a straitjacket lets you do what you want too, so long as you don't want to do anything it won't let you do, so no, it's an excellent analogy!

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 05:28:56 pm
Those 'going round in circles'
i think because one group want everything if possible readily served on silver plater, ie the built-in library, the compiler, and the (managed) language is doing the job for them, the boundary check, UB's behaviour etc. i guess thats what the profession demands for production's sake. this goes me extrapolating that what they actually wish for is a language/compiler that can read their mind or at least program a simple line DoMyProgram() and everything is done. and the other old school group (probably for hobby sake like me) still want to stick with all manual control bare down to the metal language who happily do if (i >= size) CallBackUndefineBehaviour(); or diy build a bulletproof memory management class/library for a particular resource limited HW. lets hope we extinct and lets see what the new generation/language can offer in the future, better or worse? without C...

I think, what some of the others, might want or be describing, is like an aircraft's autopilot.  But one, which doesn't have any way of switching it off or disabling it.  Which is fine and dandy, until a computer instruments failure mean you're about to crash into a giant mountain or the ground, and because the auto-pilot is always enabled/on.  There is no way for the pilots, to change the path of the aircraft, to avoid the mountain.

If anyone thinks my example is wrong.  Please look into the Boeing 737 MAX accidents.  Which involved control systems (MCAS), which the pilots couldn't disable/control (with the knowledge those particular pilots had, at the time), with disastrous results. 
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 05:41:04 pm
i dont get your analogy... what different vendor extensions? what different standards? and what are you suggesting as better alternative? i will looking forward to look up vendor extensions and different standards on the better language you are suggesting.

Arm C Language Extensions (http://file:///C:/Users/Hugh/Downloads/acle-2021Q2.pdf)

Microsoft extensions to C (https://learn.microsoft.com/en-us/cpp/build/reference/microsoft-extensions-to-c-and-cpp?view=msvc-170)

Nvidia C Language extensions (https://developer.download.nvidia.com/compute/DevZone/docs/html/C/doc/CUDA_C_Programming_Guide.pdf)

Microchip C Language extensions (https://www.puntoflotante.net/51288f.pdf)

Ahh, the old "what are you suggesting as better alternative" defense, how predictable.
you doing sort of informal fallacy on C. just because its so extensible by nature, which is imho is a big plus, so every vendors is doing extension to it in their own way, i also made my own extended library complete with bulletproof boundary check classes, so that made me the 15th standards which is bad? (but luckily i dont publish, its for my own). what do you expect? M$ style of driver certification where each vendor should comply to certain standards set by the committee? and possibly pay for the certification? M$ got heavy bashing for this, no? how could you satisfy all? are you going to make a language that only you you can extend it? good luck! python faced the same compatibility issue! on ever expanding library/extensions
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 07, 2022, 05:48:19 pm
if it is insisted that the language performs extensive safety checks, at run time, even at the lowest (system) level.  It might need to check the address is within the valid bounds of the particular array (if applicable).  It might check the value is NOT 0 (NULL), as that may indicate a possible error somewhere.
It could check the value is not less than 32, and is not too big, etc.
Possibly other safety checks could be implemented.

But then with all the extra memory accesses, comparisons, branches and other stuff.  It might take 5 or even 20 or more times longer to execute.

That's exactly how I managed to "solve" my problems  ;D

20x the code size you would get with C89 and 20x slower (-O1 is the only one implemented at the moment).
As a benefit it simplifies both ICE-testing and ICE-coverage.



Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 05:58:43 pm
you doing sort of informal fallacy on C. just because its so extensible by nature

No, that's not the fallacy of Mr. Holmes. The fallacy is that some other languages having less extensions (or idea level toy projects not needing extensions at all) prove something more than just their unpopularity.

C language is not specially "extensible" by nature. All languages are. Usual compiler extensions as showed by Holmes do not use any "extension" system built in C. They just ... are.

But every other language is the same! You totally can come up with your own Ada or Rust or Java or C# or Python compiler which accepts exactly your own command line options, deviates from the standard just as you like, or even adds keywords if you so wish. Just ... do it!

The real reason why C gets so many extensions is the popularity and wide-spread use of C, in different types of targets. When people already use C to do job X, and see X could be done better by modifying the language a bit, they ask for compiler writers to add this option. And they do it instead of coming up with a new language.

Prerequisite for this is, C has to be "kinda almost good enough". The bar does not need to be very high, but it can't be total and utter crap, either.

Part of the popularity is of course non-technical, as always. Successful technologies typically combine "good enough" with right timing and other specifics, and then they gain the momentum needed.

And the extensions have helped keep that momentum going. And I love the anger it causes in C hateboys, because in their world view, having extensions is a sign of weakness and such lead to the demise of the language, but in actual reality opposite is true, and no one is interested in admitting a weakness if you still win.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 06:00:47 pm
That's exactly how I manage to to "solved" my problems.

20x the code size you would get with C89 and 20x slower (-O1 is the only one implemented at the moment).
As a benefit it simplifies both ICE-testing(1) and ICE-coverage.

That's fine, if that is what you want.  Potentially easier/faster debugging, and possibly significantly less development time, and (for some people) disliked debugging time.

But some languages, enforce such a scenario, all the time, to varying extents.  Which means, you can't easily produce a very fast/efficient version (although other(s) have pointed out, that some modern languages, attempt to offer BOTH advantages, simultaneously (i.e. fast/efficient AND safe), by smart language design), which might be desirable, come release/production day.

If safety and/or robustness/reliability and the highest quality levels, are needed or desired.  Such flag options (in C), or languages that do things like that by default or even always.  Will be desirable for some programmers, doing some kinds of work.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on December 07, 2022, 06:07:42 pm
That's a good counter analogy.  As CPUs become ever increasingly fast, powerful and relatively low cost (for the performance you get).  The importance of compiler language's speed efficiency, gradually diminish, over the years.

From the compiler point of view unsafe Rust and Ada pragma'd to turn off runtime checks can express pretty much the same thing as equivalent C, it's the programmers which will get slower converting to Ada-SPARK and especially Rust.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 06:21:48 pm
i dont get your analogy... what different vendor extensions? what different standards? and what are you suggesting as better alternative? i will looking forward to look up vendor extensions and different standards on the better language you are suggesting.

Arm C Language Extensions (http://file:///C:/Users/Hugh/Downloads/acle-2021Q2.pdf)

Microsoft extensions to C (https://learn.microsoft.com/en-us/cpp/build/reference/microsoft-extensions-to-c-and-cpp?view=msvc-170)

Nvidia C Language extensions (https://developer.download.nvidia.com/compute/DevZone/docs/html/C/doc/CUDA_C_Programming_Guide.pdf)

Microchip C Language extensions (https://www.puntoflotante.net/51288f.pdf)

Ahh, the old "what are you suggesting as better alternative" defense, how predictable.
you doing sort of informal fallacy on C. just because its so extensible by nature, which is imho is a big plus, so every vendors is doing extension to it in their own way, i also made my own extended library complete with bulletproof boundary check classes, so that made me the 15th standards which is bad? (but luckily i dont publish, its for my own). what do you expect? M$ style of driver certification where each vendor should comply to certain standards set by the committee? and possibly pay for the certification? M$ got heavy bashing for this, no? how could you satisfy all? are you going to make a language that only you you can extend it? good luck! python faced the same compatibility issue! on ever expanding library/extensions

Did you really write "its so extensible by nature"? I've really heard it all now. Like many things in computing different people often mean different things when they use certain words. Arguably assembler lets you "do anything you want" and assembler is "extensible by nature" too. Qualities that every language possesses are obviously not qualities one can use to compare those languages.

You already know some of the reasons I think C is a poor language, I've already described some of these to you in other threads.

It has no string or bit data types, it has a contrived clumsy way to let you declare bit fields, it doesn't let you access bits in bit fields using array subscript notation, it has no support for catching and handling divide by zero or null pointer references, it treats assignments as expressions, it restricts you to always base array elements starting at zero, it restricts you to map arrays in only on direction, it forces you to "forward declare" functions, it uses the term "static" to mean "private" but in other contexts it means something else.

It has the totally useless keyword "void" which litters the source code and header files (and that has contaminated many languages since including C++, Java, C#...), it has reserved words (as do all derivatives of C). It's one of the oldest and feeblest programming languages still in regular use, it's dated, stuck in the past, hampers productivity, confuses new users with silliness like ++I and J-- and so on.

I could go on, but there's no point, you could accept at least some of these as valid criticisms rather than stubbornly defending the language no matter what I say.



Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 06:26:26 pm
From the compiler point of view unsafe Rust and Ada pragma'd to turn off runtime checks can express pretty much the same thing as equivalent C, it's the programmers which will get slower converting to Ada-SPARK and especially Rust.

The Ada-SPARK / ADA type languages, seem to need (I've not really looked into it, especially hard), the purchase, of presumably expensive compiler licenses.  Which, compared to the wide range of apparently free interpreters and compilers available, such as GCC.  Is difficult to stomach.

I.e. If we go back to the old days, when most compilers had to be paid for.  It wasn't so much of a problem, as you could choose the language you wanted, then buy it (if affordable).

But nowadays, with so much free stuff to choose between.  It is difficult to justify paying, just to use a particular language.  Perhaps for a hobby project.
I think there is an old (not up to modern standards), open source, free version of ADA, floating about.  But if I remember correctly, it seemed too old and using outdated language specifications, to try out.

If compilers should be free or not, I suppose is another topic of conversation.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 06:28:57 pm
From the compiler point of view unsafe Rust and Ada pragma'd to turn off runtime checks can express pretty much the same thing as equivalent C, it's the programmers which will get slower converting to Ada-SPARK and especially Rust.

The Ada-SPARK / ADA type languages, seem to need (I've not really looked into it, especially hard), the purchase, of presumably expensive compiler licenses.  Which, compared to the wide range of apparently free interpreters and compilers available, such as GCC.  Is difficult to stomach.

I.e. If we go back to the old days, when most compilers had to be paid for.  It wasn't so much of a problem, as you could choose the language you wanted, then buy it (if affordable).

But nowadays, with so much free stuff to choose between.  It is difficult to justify paying, just to use a particular language.  Perhaps for a hobby project.
I think there is an old (not up to modern standards), open source, free version of ADA, floating about.  But if I remember correctly, it seemed to old and using outdated language specifications, to try out.

If compilers should be free or not, I suppose is another topic of conversation.

I do think the standards documents should be free, some of the stuff on the ANSI standards website could be given away, not making standards free hampers their spread I think.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 06:34:31 pm
It has no string or bit data types, it has a contrived clumsy way to let you declare bit fields, it doesn't let you access bits in bit fields using array subscript notation, it has no support for catching and handling divide by zero or null pointer references, it treats assignments as expressions, it restricts you to always base array elements starting at zero, it restricts you to map arrays in only on direction, it forces you to "forward declare" functions, it uses the term "static" to mean "private" but in other contexts it means something else.

It has the totally useless keyword "void" which litters the source code and header files (and that has contaminated many languages since including C++, Java, C#...), it has reserved words (as do all derivatives of C). It's one of the oldest and feeblest programming languages still in regular use, it's dated, stuck in the past, hampers productivity, confuses new users with silliness like ++I and J-- and so on.
man i think i'm pretty clear what you are after. i dont want to go further with this type of argument, you have every right to not be happy with it. will be looking forward to see your new invention.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 07, 2022, 06:36:38 pm
The Ada-SPARK / ADA type languages

Direct experience: AdaMulti(GreenHills) + Trace/Nexus(Lauterbach).
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 07, 2022, 06:39:42 pm
Part of the popularity is of course non-technical, as always

"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 07, 2022, 06:43:35 pm
Part of the popularity is of course non-technical, as always
"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)
make your own! just dont make another confusing/non-compliance standard such as printf2 or ditbho_printf, unless for your own.. ;D
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: mfro on December 07, 2022, 06:52:19 pm
The Ada-SPARK / ADA type languages, seem to need (I've not really looked into it, especially hard), the purchase, of presumably expensive compiler licenses.  Which, compared to the wide range of apparently free interpreters and compilers available, such as GCC.  Is difficult to stomach.

GNAT (GNU Ada) comes at the exact same cost as any other GNU compiler: zero. It passes 100% of ACATS (kind of an Ada standards compliance test).
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 07:01:20 pm
The Ada-SPARK / ADA type languages, seem to need (I've not really looked into it, especially hard), the purchase, of presumably expensive compiler licenses.  Which, compared to the wide range of apparently free interpreters and compilers available, such as GCC.  Is difficult to stomach.

GNAT (GNU Ada) comes at the exact same cost as any other GNU compiler: zero. It passes 100% of ACATS (kind of an Ada standards compliance test).

Thanks, that is interesting to know.   :)

I think because I (previously), only had a rather/very quick scan of Ada (There are so many millions of different, new/upcoming programming languages these days), it is difficult to keep up.
I mainly looked at the commercial Ada site.  Which claimed so many tempting features, for the paid compiler.  It put me off, from taking the free GNU Ada compiler seriously, after that point.

But obviously, that company (who sell the Ada compiler), have a special interest, in claiming their paid for compiler, is THE compiler to get.

I vaguely remember there was some feature I really wanted which the paid compiler had, but the free one didn't.  But my recollection is too weak to remember exactly.

EDIT:
Tried to find it, and I think it was this:
https://www.adacore.com/about-ada (https://www.adacore.com/about-ada)

I wanted one or more of the 'new' Ada 2012 features in that big feature matrix.  But rightly or wrongly, had decided the free (GNU etc) compilers, didn't support it (Ada 2012), so I wouldn't get the desired feature(s).

Since the price is marked 'Request pricing'.  I assumed, it wasn't set to a price, that would attract hobby project budget compilers.

I.e. If something says 'Request Pricing' as an option, rather than specifying the actual price.  I assume, the price is going to be (silly) expensive and/or these days, not only a huge amount of money, but also, needs renewing, every 12 months.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 07, 2022, 07:01:46 pm
If you can't live with occasional snags, don't use a scalpel. Scalpels are for professionals only.

If you can't live with C's UB concept, don't use C. C is a sharp blade as well.

The problem is that very few programmers understand all the subtle and surprising causes of "undefined behaviour". Most think they do, of course :( That was famously illustrated when Hans Boehm thought it worthwhile to write a paper pointing out that you couldn't write a threading library in C - too many people presumed or "thought" you could.

C++ is worse. The committee defining the language didn't understand what they had created until their noses were rubbed in it by a short program that spat out the sequence of prime numbers while it ws being compiled. That's right; the design committee hadn't realised C++ templates are a Turing complete language in themselves - and that some valid C++ programs could never finish being compiled.

The least unsatisfactory alternative with C is to adhere to one of the relatively benign subsets of C, e.g.  MISRA.

If you cover the scalpel, with cotton wool, safety tape and other precautions, making it so that even a toddler, could use it safely.

What do you think would happen to a patient, that urgently needs an operation to save their life, if the only tool available, was the aforementioned, scalpel?

If a tricky embedded system, needs to perform a very rapid software operation, in order to work, safely and correctly, otherwise, the voltage/system/etc will change too much (in real-time), ruining the motor controller, or whatever the system/software is trying to do.

Then your suggested 'new' language, i.e. NOT very high speed/efficient C, may make the task relatively unsolvable with the existing/affordable hardware.

In other words.  Use the RIGHT TOOL for the RIGHT JOB.  Not some film-flamcy cotton wool, safety tape covered, thing, that is not suitable for doing the job in hand.

I have not suggested another language, except the xC+xCORE exosystem which guarantees timing in a way no other ecosystem does. A 4000MIPS processor isn't slow :)

The right tool for the kind of job you mention is emphatically not C.

Candidates might include Ada or subsets such as MISRA C or SPARK Ada.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 07, 2022, 07:12:00 pm
From the compiler point of view unsafe Rust and Ada pragma'd to turn off runtime checks can express pretty much the same thing as equivalent C, it's the programmers which will get slower converting to Ada-SPARK and especially Rust.

The Ada-SPARK / ADA type languages, seem to need (I've not really looked into it, especially hard), the purchase, of presumably expensive compiler licenses.  Which, compared to the wide range of apparently free interpreters and compilers available, such as GCC.  Is difficult to stomach.

I.e. If we go back to the old days, when most compilers had to be paid for.  It wasn't so much of a problem, as you could choose the language you wanted, then buy it (if affordable).

But nowadays, with so much free stuff to choose between.  It is difficult to justify paying, just to use a particular language.  Perhaps for a hobby project.
I think there is an old (not up to modern standards), open source, free version of ADA, floating about.  But if I remember correctly, it seemed too old and using outdated language specifications, to try out.

If compilers should be free or not, I suppose is another topic of conversation.

In a professional context, the cost of a compiler is irrelevant. That cost is dwarfed by other NRE costs: just consider the cost of a failure in the field, or the costs associated with specification, design, implementation, debugging and integration with other systems. There are other non-technical costs as well, of course.

In an amateur context, the cost of a compiler is dominant.

I'm confused as to whether you are considering amateur or professional devices.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 07:17:27 pm
I'm confused as to whether you are considering amateur or professional devices.

In that context, Hobby/fun use.  A new, hopefully robust language to play with, and maybe do some stuff with.

I agree.  If it involves a workplace/business, the cost is often irrelevant.  Unless it is very significantly overpriced.  Which some people think Altium PCB is.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Siwastaja on December 07, 2022, 07:48:17 pm
I could go on, but there's no point, you could accept at least some of these as valid criticisms rather than stubbornly defending the language no matter what I say.

You misinterpret others because you are not paying attention, and because we are making it worse by making fun of your blindness.

Everyone agrees with (nearly) all points in that list of criticisms. There are good counter-points to many of those (more like explanations why it is so, not that it makes it any better), but not all, some are just objectively very stupid, such as the messed-up double use of keyword static.

It's just we have heard all of this thousands of times, we all know about it, and we agree with it.

So what's next? We want to hear constructive ideas how it could be done better. You got a pretty bad start with your thread because your mixed bag of random ideas, some just poorly though out syntactic sugar which does not taste any better than the "static" mess in C, just different, some having consequences in memory footprint making your language not suitable for small microcontrollers, contrary to the thread title, and so on and so on. Combined with an extremely overconfident "I know this stuff and you don't" attitude. A bad mix; assholes like me are tolerated when we are at least right or have good ideas 95% of the time.

So instead of repeating the "C is crap" ad nauseam, which we alreardy know, try something new. Or don't, finally it doesn't matter.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on December 07, 2022, 07:56:33 pm
"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)

Printf has also been a big cause of exploits BTW. But I can't really blame that purely on C, it's as much because of bad design ideas put in stone during the Unix era regardless of C. Combining escape sequences with un-trusted text input is an atrociously bad idea. By now it's so entrenched, people can't even conceive of alternatives.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 08:24:16 pm
I could go on, but there's no point, you could accept at least some of these as valid criticisms rather than stubbornly defending the language no matter what I say.

You misinterpret others because you are not paying attention, and because we are making it worse by making fun of your blindness.

Everyone agrees with (nearly) all points in that list of criticisms. There are good counter-points to many of those (more like explanations why it is so, not that it makes it any better), but not all, some are just objectively very stupid, such as the messed-up double use of keyword static.

It's just we have heard all of this thousands of times, we all know about it, and we agree with it.

So what's next? We want to hear constructive ideas how it could be done better. You got a pretty bad start with your thread because your mixed bag of random ideas, some just poorly though out syntactic sugar which does not taste any better than the "static" mess in C, just different, some having consequences in memory footprint making your language not suitable for small microcontrollers, contrary to the thread title, and so on and so on. Combined with an extremely overconfident "I know this stuff and you don't" attitude. A bad mix; assholes like me are tolerated when we are at least right or have good ideas 95% of the time.

So instead of repeating the "C is crap" ad nauseam, which we alreardy know, try something new. Or don't, finally it doesn't matter.

We think you are the one being repetitive, you've expressed nothing but cynicism to the suggestion that a new language could be designed, suggested nothing you'd like to see in a new language. I asked what people would like to see in a new language, you've not shared any of the kinds of features you'd find helpful or valuable, We've been asking and you and one or two others have repeatedly done little more than dismiss the idea altogether, express contempt for such an idea.

You ask "I want to hear constructive ideas" yet ignore the very posts that contained some of the possible areas one could look at, e.g.

Quote

There are several things that a new language would bring, here's a summary of the more salient:

  • No reserved words, thus enabling new keywords to be added over time.
  • Support 'bit' as a native data type.
  • Support 'strings' as a native type, BCD/decimal as well.
  • Support for namespaces.
  • Computed gotos.
  • Flexible alignment, packing and padding directives.
  • Nested functions.
  • Precision timing features like emit multiple NOP operations or ensure identical execution time for (say) case clauses in a switch.
  • Support for an async/await model.

These are the kinds of things that I've seen other people raise or complain about sometimes, things that a freshly designed language could readily accomodate.


and

Quote

At a minimum the language would include:

1. More storage classes than C (defined, based etc)
2. More data types including decimal/BCD and strings of fixed or variable length.
3. Arbitrary rank arrays with optional bound specifiers.
4. Distinguish between function and procedures.
5. Fine control over padding and alignment and field ordering etc.
6. No object oriented features, no GC, no virtual functions and so on.
7. No need for "forward declarations"
8. Nested functions/procedures.
9. Some kind of "computed" goto support.
10. No reserved words.
11. No explicit pointer arithmetic, like ptr++ and ptr-- and so on.
12. Invocable variables (a simpler form of C's function pointer)

That's the basic initial list anyway, entirely reasonable and feasible and something I've implemented successfully in the past.

I also looked into the possible design of coroutine support and literals that allow space as separators for binary, octal, hex and decimal and nested procedures and an initialization operator for any kind of type or aggregate data structure, and Unicode UTF-8 support and the possibility of having a keyword dictionaries for different languages like French, Spanish, German and so on, but nothing from you, not a peep just endless complaining about the fact someone dares to broach the subject with you.

So why do you say "I want to hear constructive ideas" when you pretty obviously do not, actions speak louder than words and so far you've made no meaningful suggestions or contributions to the discussion.

Please do not presume to describe me as over confident either, that's another of your regular insulting remarks, do not try project your own inadequacies onto others please.




Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: MK14 on December 07, 2022, 08:32:50 pm
I don't think you should be posting big chunks of stuff from a DIFFERENT thread, and discussing it in this one.
Best to keep the discussion to that other 17+? page thread.

Because it will just cause too much confusion, and damage/destroy/off-topic this thread, which somewhat belongs to someone else and/or this forum.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 07, 2022, 08:38:05 pm
I don't think you should be posting big chunks of stuff from a DIFFERENT thread, and discussing it in this one.
Best to keep the discussion to that other 17+? page thread.

Because it will just cause too much confusion, and damage/destroy/off-topic this thread, which somewhat belongs to someone else and/or this forum.

I think you are right, I will do that, my post was a reaction to Siwastaja's (https://www.eevblog.com/forum/programming/should-c-language-undefined-behaviour-cover-crashinghanging/msg4568008/#msg4568008) post above though, he brought that thread up and I simply wanted to counter his unfounded claims.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 07, 2022, 08:48:58 pm
"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)

Printf has also been a big cause of exploits BTW.

Yep. Now, as I just said in another thread, exploits are often more due to lack of proper input validation than on the function itself.

Think prevention vs. protection. But it's always easier to blame one's tools.

But I can't really blame that purely on C, it's as much because of bad design ideas put in stone during the Unix era regardless of C. Combining escape sequences with un-trusted text input is an atrociously bad idea. By now it's so entrenched, people can't even conceive of alternatives.

It's a relatively bad idea given how it can go bad in so many ways, but I can understand the appeal. Formatted printing is convenient to use. Re-read the thread about printf() alternatives, many people don't want to have to deal with alternatives that require more programming effort. A format string is easy to use and (relatively) easy to read, and while much more elaborate ways of implementing them in a safer way are possible, that was certainly out of the question back in the early 70's.

But anyway - you just pinpointed the issue, as I said above.

VALIDATE YOUR INPUTS.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 07, 2022, 11:58:32 pm
it's the same with php: sanitize your fields -> validate your inputs
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: hamster_nz on December 08, 2022, 05:08:28 am
I would love to hear Sherlock Holmes's thoughts on PASCAL. It was around at about the same time as C in the early adoption of PCs, and a far more 'designed' language. "Turbo Pascal" and "Turbo C" were approximately equal languages at tools, and I've used both.

Why did PASCAL not win, given its technical superiority?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 08, 2022, 05:19:09 am
It has largely survived though, mainly through Delphi (which despite what people may think, still has a large user base. It's just a much more silent crowd. Maybe because the stuff just works.)
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on December 08, 2022, 05:34:11 am
It's a relatively bad idea given how it can go bad in so many ways, but I can understand the appeal. Formatted printing is convenient to use. Re-read the thread about printf() alternatives, many people don't want to have to deal with alternatives that require more programming effort. A format string is easy to use and (relatively) easy to read

The format string should be a constant string literal or only allow formatting (with text passed in as %s arguments) and returning an error on any other text in the format string.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 08, 2022, 07:47:43 am
"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)

Printf has also been a big cause of exploits BTW.

Yep. Now, as I just said in another thread, exploits are often more due to lack of proper input validation than on the function itself.

Think prevention vs. protection. But it's always easier to blame one's tools.

But I can't really blame that purely on C, it's as much because of bad design ideas put in stone during the Unix era regardless of C. Combining escape sequences with un-trusted text input is an atrociously bad idea. By now it's so entrenched, people can't even conceive of alternatives.

It's a relatively bad idea given how it can go bad in so many ways, but I can understand the appeal. Formatted printing is convenient to use. Re-read the thread about printf() alternatives, many people don't want to have to deal with alternatives that require more programming effort. A format string is easy to use and (relatively) easy to read, and while much more elaborate ways of implementing them in a safer way are possible, that was certainly out of the question back in the early 70's.

But anyway - you just pinpointed the issue, as I said above.

VALIDATE YOUR INPUTS.


c is not about safety nor protection to your heart content. Its just 'minimally works' i mean its standard library.. if anyone not happy with it, make another safe library on your own, dont use the standard printf, as the OP has figured out.. but then there's people on enterprise grade who want everything ready on silver platter safe and sound, regardless of what holy excuses you give them.. so its futile.. hows the NSA and CIA deals with SW things? What alternative? Visual Basic has been around for ages and pretty much covers everything mentioned here, about boundary check and safety exceptions.. its the most charming human friendly syntax, options to do safety boundary check, vs optimize for speed code during compilation etc etc, but it never went as popular and long lived as C, everybody went to bloated java or python. Siwastaja possibly explained it. Nothing technical, just support ecosystem, marketing, about the right timing or even money laundering whatever that made a language go, even if its crappier than the earlier.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 08, 2022, 08:02:40 am
I would love to hear Sherlock Holmes's thoughts on PASCAL. It was around at about the same time as C in the early adoption of PCs, and a far more 'designed' language. "Turbo Pascal" and "Turbo C" were approximately equal languages at tools, and I've used both.

Why did PASCAL not win, given its technical superiority?
i got the chance to try out Borland C++ Builder, Borland Delphi (GUI version using Pascal) and MSVStudio... those are were expensive and highly regarded IDE tools... i ditched the former 2 and stick with MSVS (C++ Studio and VB)  just because i cant get them to work with my own diy custom dll/api... MSVS solved pretty much everything mentioned/suggested/proposed in every threads in this forum since ages.. so..  :popcorn:
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 08, 2022, 11:58:11 am
I would love to hear Sherlock Holmes's thoughts on PASCAL. It was around at about the same time as C in the early adoption of PCs, and a far more 'designed' language. "Turbo Pascal" and "Turbo C" were approximately equal languages at tools, and I've used both.

Why did PASCAL not win, given its technical superiority?

My understanding is pretty much the same as this, I think this explanation fits the facts.

https://qr.ae/pvcWaV

First almost always beats best. Look at the crippled Intel CPU used in the IBM PC, the 68000 was head and shoulders above Intel, yet by comparison became like Pascal. Intel's crippled CPU was simply ready earlier, the rest is history.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 08, 2022, 02:22:30 pm
Here's an extremely thought provoking blog post (http://trevorjim.com/if-johnny-cant-patch-maybe-he-shouldnt-use-c-c++/) about languages, particularly about the cause of memory corruption, is it the language or the programmer...

I loved this:

Quote
The P0 spin on this myth is: if you’ve made a bug, make sure you don’t make another bug when you fix the first bug.

That would be nice, but, really? Programmers are supposed to take their usual process, which produced the bug in the first place, and turn on INFALLIBLE MODE so that there is no bug in the patch? How likely is that?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 08, 2022, 08:04:15 pm
Here's an extremely thought provoking blog post (http://trevorjim.com/if-johnny-cant-patch-maybe-he-shouldnt-use-c-c++/) about languages, particularly about the cause of memory corruption, is it the language or the programmer...

I loved this:

Quote
The P0 spin on this myth is: if you’ve made a bug, make sure you don’t make another bug when you fix the first bug.

That would be nice, but, really? Programmers are supposed to take their usual process, which produced the bug in the first place, and turn on INFALLIBLE MODE so that there is no bug in the patch? How likely is that?

I don't really see the thought provoking factor here. He pretty much says what almost everyone else does. How is that provoking anything?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: hamster_nz on December 08, 2022, 08:45:19 pm
I would love to hear Sherlock Holmes's thoughts on PASCAL. It was around at about the same time as C in the early adoption of PCs, and a far more 'designed' language. "Turbo Pascal" and "Turbo C" were approximately equal languages at tools, and I've used both.

Why did PASCAL not win, given its technical superiority?

My understanding is pretty much the same as this, I think this explanation fits the facts.

https://qr.ae/pvcWaV

First almost always beats best. Look at the crippled Intel CPU used in the IBM PC, the 68000 was head and shoulders above Intel, yet by comparison became like Pascal. Intel's crippled CPU was simply ready earlier, the rest is history.

Gosh, that very much differs from my recollection. Here's mine:

PASCAL predated C by a few years and was also commonly available. I remember using it on an Apple II and it was often seen in the press (e.g. Byte Magazine, Dr Dobbs, books at the bookstore...). It took over as the preferred language for introductory CompSci at University (until it got pushed out by Java in the late 90s). Its syntax was also used as the bases for most academic pseudocode you find in books of that era.

What killed Pascal was:


This was all at a time where business applications were largely written in something else - either in COBOL or one of the many 4GL development tools like DBase, FoxPro, DataFlex, Magix, Pick, etc. Almost nobody was writing business applications in C.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 08, 2022, 08:59:20 pm
Yup.

But Turbo Pascal, especially the later versions, solved most of these issues. By the latest versions, it had become a very capable language with a lot more going for it than C, like units (which were Pascal modules), a clean programming model, etc. But at this point it was too late for two main reasons IMO: first, C had become king on Unix-like system AND Windows (C was still the primary dev language on Windows until the late 90's), then C++ took over, and later Java for application programming.

Yep, C was king for Windows app development for most of the 90's. Remember the famous Petzold books. C++ on Windows only really started taking over in the second half of the 90's.

And Pascal still had this "academic" image linked to it. But the interesting part is that it has survived, not only in all the languages it inspired, but also as Delphi/Object Pascal which is still used.

Anyway, it's all history, but as always, popularity often has very little to do with technical merits.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: berke on December 08, 2022, 09:30:54 pm
People don't realize how much of a technological achievement Rust is.  Previously that kind of type safety, strength and expressivity was only available in garbage collected languages such as OCaml or Haskell where directly playing with hardware is a huge pain.  Now it's available with no runtime overhead.

In a C world, if you have to call third-party code, that code can corrupt memory (or registers) in a subtle way undetectable to all the Valgrinds of the world, and you'll spend two months looking for a bug that appeared to be in your code but was some weird memory management race condition in the third party library that was corrupting a few bits in your code.

In Rust you can safely call third-party code.  If they assure you they don't use unsafe Rust, you automatically know that your code will not crash because of their code.  If it does, it's a rare compiler fault or a hardware issue.  It's not going to crash as in segmentation fault to begin with.  If it's buggy it's not going to corrupt memory in unpredictable ways.  The whole language has been designed from the ground-up to prevent that.  The compiler checks all the code, all the branches, all the cases, with one hundred percent coverage.

This also means you can hire junior devs (or foreign spies) and they're not going to make your software unstable, at least in ways unrelated to your business logic.

The main drawback is that you're gonna have a bad time if your code has allocated structures with pointers all over the place.  That's not something that can be automatically proven memory-safe.  (That's what the Rust compiler does, it literally automatically and mathematically proves that your code is memory safe, or gives you a counter-example.)  So you'll have to wrap everything within reference-counted, mutex'ed pointers and that's painful.  For code like that, use a GC'd language.

Another drawback is that the compiler and standard library codebase (including LLVM) is ginormous, you need gigabytes to compile something and it's CPU intensive (but so is C++).  A decent C compiler takes very little memory.

But You can use Rust to produce code for small devices, but not on small devices.

Speaking of which you can also write low-level embedded code in Rust (check out the embedded-hal crate), but of course you'll have to write some unsafe code to encapsulate ISRs or other hardware accesses.  Those parts can be written by the more experienced developers and provided as safe functions for the interns to use without crashing the system.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 08, 2022, 10:05:48 pm
Here's an extremely thought provoking blog post (http://trevorjim.com/if-johnny-cant-patch-maybe-he-shouldnt-use-c-c++/) about languages, particularly about the cause of memory corruption, is it the language or the programmer...

I loved this:

Quote
The P0 spin on this myth is: if you’ve made a bug, make sure you don’t make another bug when you fix the first bug.

That would be nice, but, really? Programmers are supposed to take their usual process, which produced the bug in the first place, and turn on INFALLIBLE MODE so that there is no bug in the patch? How likely is that?

I don't really see the thought provoking factor here. He pretty much says what almost everyone else does. How is that provoking anything?

Well it just provoked a response from you didn't it, I presume you think before you respond, in which case you have your answer.



Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 08, 2022, 10:14:21 pm
I would love to hear Sherlock Holmes's thoughts on PASCAL. It was around at about the same time as C in the early adoption of PCs, and a far more 'designed' language. "Turbo Pascal" and "Turbo C" were approximately equal languages at tools, and I've used both.

Why did PASCAL not win, given its technical superiority?

My understanding is pretty much the same as this, I think this explanation fits the facts.

https://qr.ae/pvcWaV

First almost always beats best. Look at the crippled Intel CPU used in the IBM PC, the 68000 was head and shoulders above Intel, yet by comparison became like Pascal. Intel's crippled CPU was simply ready earlier, the rest is history.

Gosh, that very much differs from my recollection. Here's mine:

PASCAL predated C by a few years and was also commonly available. I remember using it on an Apple II and it was often seen in the press (e.g. Byte Magazine, Dr Dobbs, books at the bookstore...). It took over as the preferred language for introductory CompSci at University (until it got pushed out by Java in the late 90s). Its syntax was also used as the bases for most academic pseudocode you find in books of that era.

What killed Pascal was:

  • Early versions of Pascal didn't compile to native code. It ended up in a 'p-code' ( https://en.wikipedia.org/wiki/P-code_machine ) . This was great for portability, but poor for performance. You could not extract the full power of the machine - if you needed to you used something else. It valued portability above performance
  • it wasn't flexible enough. Pascal had a runtime model that was very hard to get rid of, making writing system level code very challenging. With C you pretty much abandon the runtime library and do your own thing. This made Pascal unsuited to writing low-level code like building OSes.
  • Code performance. When the first advanced optimizing C compilers came out PASCAL got left behind in performance. C's crudeness made for intermediate code that was easier to analyze and optimize in the resource constrained environments of the time. You ended up with smaller, faster code when you used C.
  • Pascal users would still need to use assembly for performance critical code. C would let you replace most of your assembly code with something that could be more easily developed and maintained. It was not at all uncommon for Pascal users to link to modules written in C code for performance reasons - much like how Python used now interface to C when needed. Most developers were of the view that if you are going to invest time implementing your critical code in C, you may as well use it for the rest of your codebase.

This was all at a time where business applications were largely written in something else - either in COBOL or one of the many 4GL development tools like DBase, FoxPro, DataFlex, Magix, Pick, etc. Almost nobody was writing business applications in C.

His article openly mentioned p-code. He also explained that C compiler source was freely available in universities opening the door to retargeting, Pascal compiler source wasn't as easy to come by, people had to pay for it.

The p-code was not Pascal, the compiler turned the source into pascal but could have turned it into a CPU specific object code, many Pascal compilers later did so.

So Pascal's "performance" isn't anything to do with the language itself but the compiler and code generator and optimizer.  The reasons that Pascal is less prevalent than C is nothing to do with any linguistic qualities but circumstances.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 08, 2022, 10:30:58 pm
The reasons that Pascal is less prevalent than C is nothing to do with any linguistic qualities but circumstances.
define circumstances. if its including the fact that pascal is technically less capable than C, then you are right. nobody cares about linguistic if its capable enough.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 08, 2022, 10:54:18 pm
The reasons that Pascal is less prevalent than C is nothing to do with any linguistic qualities but circumstances.
define circumstances. if its including the fact that pascal is technically less capable than C, then you are right. nobody cares about linguistic if its capable enough.

I mean events, decisions, trends like Unix (which included C compilers) being given away free to universities, universities using that as a basis for some courses, students seeing examples of OS schedulers, utilities and network code all written in C and so on. Circumstances like Sun adopting Unix as the basis for their software strategy. As that person stated, Unix was developed by Bell Labs, which was part of a government-protected monopoly. The Unix OS and the multitude of tools it has were all written in C, therefore wherever Unix will go, C must follow.

Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL, yes, even assembler - they are all examples of Turing machines.

So if two languages can each be used to convert some input into some output, then how can you compare the languages? How do you define "technically capable"? What is all this "linguistics" stuff? (The joke here is on you, because you can't define "technically capable" without referring to linguistic properties !  :-DD )

nobody cares about linguistics if the language is capable enough.

One of the most amusing oxymorons I've seen this year!

What if we counted the number of buffer overrrun bugs per 1,000 lines of code, for C and Pascal across some reasonable sized sample, would that be a meaningful metric perhaps? an indicator of technical capability?

There is no input text that can be converted to some output only by using C, if you know of one, please share it.



Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 09, 2022, 05:53:30 am
nobody cares about linguistics if the language is capable enough.
One of the most amusing oxymorons I've seen this year!
you dont want to get an insult when i ask if its your place to comment C? (which clearly you are not!) but yet you are happy to give direct insult to others (in this case... me) when we give you our opinion (when you have nothing else better point or recent news to say)... how ironic! the new X generation on the street! that we worth ignoring! ;D

I mean events, decisions, trends like Unix (which included C compilers) being given away free to universities, universities using that as a basis for some courses, students seeing examples of OS schedulers, utilities and network code all written in C and so on. Circumstances like Sun adopting Unix as the basis for their software strategy. As that person stated, Unix was developed by Bell Labs, which was part of a government-protected monopoly. The Unix OS and the multitude of tools it has were all written in C, therefore wherever Unix will go, C must follow.
thats the history lesson and you got so left behind.. i ask you about today's events/circumstances... even though there are ecosystem such as borland delphi or embarcadero, why no body cares (or only minority?) to make another latest extension/development like free tools based on pascal language? or its structure/idea etc... at least not as popular as C/C++? there is no pascal++ to support operator overloading, polymosphism/template and i can find more... so bye bye pascal... your history lesson is a dissapointment/boring esp from someone who claimed a proficient programmer who built a big compiler... ;D
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: mfro on December 09, 2022, 06:45:37 am
Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL
Actually, you can't. At least not with the same level of control as you have in C. With the exception of C# (that has the same), none of the languages has any equivalent to the volatile expression to control the exact point of register loads and stores.

That either leaves you with the choice of not having certain optimisations or the inability to reliably write interrupt/exception handlers.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: DiTBho on December 09, 2022, 08:14:56 am
Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL, yes, even assembler - they are all examples of Turing machines.

time/effort independent assumption -> human being resources are limited -> wrong.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 02:33:38 pm
Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL
Actually, you can't. At least not with the same level of control as you have in C. With the exception of C# (that has the same), none of the languages has any equivalent to the volatile expression to control the exact point of register loads and stores.

That either leaves you with the choice of not having certain optimisations or the inability to reliably write interrupt/exception handlers.

First, do you agree that we can't compare languages without talking about programming language syntax and semantics? We can't say C has a greater "level of control" unless we define what that means in linguistic terms? unless we can quantitatively measure that?

Second, my question was is there an input that can be consumed to produce an output that cannot be achieved with another language consuming the same input, and if there is an example.

I think the answer to that is "no", if you disagree then we can explore that if you want.

As for "volatile" it typically has different semantics in different languages, so right away its hard to compare languages on that basis. More importantly "volatile" is nothing to with the language, it is simply a way of influencing the code optimizers and optimizers are an implementation matter not a language issue.

Volatile is a way of saying to the optimizer "please don't rewrite these parts of my code, please ensure the codes does exactly what I wrote".









Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: mfro on December 09, 2022, 03:19:26 pm
Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL
Actually, you can't. At least not with the same level of control as you have in C. With the exception of C# (that has the same), none of the languages has any equivalent to the volatile expression to control the exact point of register loads and stores.

That either leaves you with the choice of not having certain optimisations or the inability to reliably write interrupt/exception handlers.

First, do you agree that we can't compare languages without talking about programming language syntax and semantics? We can't say C has a greater "level of control" unless we define what that means in linguistic terms? unless we can quantitatively measure that?

Umm, no. First and foremost, I need a language that suits my needs. A programming language is a tool and tools aren't rated by beauty contest, the only measure that counts is if it they get the job done.

Second, my question was is there an input that can be consumed to produce an output that cannot be achieved with another language consuming the same input, and if there is an example.

I think the answer to that is "no", if you disagree then we can explore that if you want.
That question is nonsense, IMHO. What you request is us to prove that there are languages that are not Turing complete. By definition, programming languages have to be Turing complete or they don't deserve that designation. I won't discuss if a rose is a rose.

As for "volatile" it typically has different semantics in different languages, so right away its hard to compare languages on that basis. More importantly "volatile" is nothing to with the language, it is simply a way of influencing the code optimizers and optimizers are an implementation matter not a language issue.

Volatile is a way of saying to the optimizer "please don't rewrite these parts of my code, please ensure the codes does exactly what I wrote".

Volatile has exactly one single semantic in C and C[derived] languages. And it provides required functionality to write proper exception handlers and multithreaded interprocess communication. C is *the* system programming language, if you like it or not.

I like PASCAL (and Modula II and Oberon), I even like Ada, but (except maybe for Ada, that indeed provides volatile) I'd never come up with the idea of attempting to write any code that directly needs to interact with hardware (or deal with multiple processors) in one of these languages.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 03:24:31 pm
nobody cares about linguistics if the language is capable enough.
One of the most amusing oxymorons I've seen this year!
you dont want to get an insult when i ask if its your place to comment C? (which clearly you are not!) but yet you are happy to give direct insult to others (in this case... me) when we give you our opinion (when you have nothing else better point or recent news to say)... how ironic! the new X generation on the street! that we worth ignoring! ;D

I apologize if that seemed insulting.

I was trying emphasize though how being dismissive of language theory, principles and so on, is self contradictory. Saying you want to discuss the merits of C as a language while at the same time sidelining formal aspects of language design, grammars and so on, is self contradictory, that's the point I wanted to make.

I mean events, decisions, trends like Unix (which included C compilers) being given away free to universities, universities using that as a basis for some courses, students seeing examples of OS schedulers, utilities and network code all written in C and so on. Circumstances like Sun adopting Unix as the basis for their software strategy. As that person stated, Unix was developed by Bell Labs, which was part of a government-protected monopoly. The Unix OS and the multitude of tools it has were all written in C, therefore wherever Unix will go, C must follow.

Thats the history lesson and you got so left behind.. i ask you about today's events/circumstances... even though there are ecosystem such as borland delphi or embarcadero, why no body cares (or only minority?) to make another latest extension/development like free tools based on pascal language? or its structure/idea etc... at least not as popular as C/C++? there is no pascal++ to support operator overloading, polymosphism/template and i can find more... so bye bye pascal... your history lesson is a dissapointment/boring esp from someone who claimed a proficient programmer who built a big compiler... ;D

You actually asked me to "define circumstances", you wanted to know what I meant by the term and so I told you. It wasn't a "history lesson" it was a clarification of what I meant by "circumstances". The rest of that paragraph makes no sense to me, it sound like you disagree with something I might have said but I do know what that is.







Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 03:46:15 pm
Anything you can write in C you can write in Pascal or C# or PL/I or COBOL or APL
Actually, you can't. At least not with the same level of control as you have in C. With the exception of C# (that has the same), none of the languages has any equivalent to the volatile expression to control the exact point of register loads and stores.

That either leaves you with the choice of not having certain optimisations or the inability to reliably write interrupt/exception handlers.

First, do you agree that we can't compare languages without talking about programming language syntax and semantics? We can't say C has a greater "level of control" unless we define what that means in linguistic terms? unless we can quantitatively measure that?

Umm, no. First and foremost, I need a language that suits my needs. A programming language is a tool and tools aren't rated by beauty contest, the only measure that counts if it they get the job done.

I see, so you disagree, OK show me the data processing test that cannot be solved by another language. Yes a language should meets one's need, no argument with that. Yes a programming language is a tool, no argument with that. If you can't define how languages are compared then how do you know that C is the best choice?

What is it about a programming language specifically, that helps you "get the job done"? You mentioned "volatile" and that's fine, I pointed out though that that's not a matter of language, its more about how a language is implemented.


Second, my question was is there an input that can be consumed to produce an output that cannot be achieved with another language consuming the same input, and if there is an example.

I think the answer to that is "no", if you disagree then we can explore that if you want.
That question is nonsense, IMHO. What you request is us to prove that there are languages that are not Turing complete. By definition, programming languages have to be Turing complete or they don't deserve that designation. I won't discuss if a rose is a rose.

Well if a program written in C cannot do any more than a program written in other languages then how can you compare languages? I already suggested one possible metric, the frequency of buffer overrun bugs as a function of language, you never commented on that idea.


As for "volatile" it typically has different semantics in different languages, so right away its hard to compare languages on that basis. More importantly "volatile" is nothing to with the language, it is simply a way of influencing the code optimizers and optimizers are an implementation matter not a language issue.

Volatile is a way of saying to the optimizer "please don't rewrite these parts of my code, please ensure the codes does exactly what I wrote".

Volatile has exactly one single semantic in C and C[derived] languages. And it provides required functionality to write proper exception handlers and multithreaded interprocess communication. C is *the* system programming language, if you like it or not.

I like PASCAL (and Modula II and Oberon), I even like Ada, but (except maybe for Ada, that indeed provides volatile) I'd never come up with the idea of attempting to write any code that directly needs to interact with hardware (or deal with multiple processors) in one of these languages.

That's all well and good but once again "volatile" pertains to the implementation of a language not the language itself. Furthermore, saying "Volatile has exactly one single semantic in C" is quite simply untrue, I quote: (emphasis mine)

Quote
In C, and consequently C++, the volatile keyword was intended to

o - allow access to memory-mapped I/O devices
o - allow uses of variables between setjmp and longjmp
o - allow uses of sig_atomic_t variables in signal handlers.

While intended by both C and C++, the C standards fail to express that the volatile semantics refer to the lvalue, not the referenced object. The respective defect report DR 476 (to C11) is still under review with C17.[2]

Here is that defect report (https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm#dr_476). Here is a quote too, from it:

Quote
The following sections discuss the C semantics of the volatile keyword and show that they neither support existing practice nor, we believe, reflect the intent of the committee when they were crafted.

It's meaning varies, it has a different meaning in C# a different meaning in Java and so on.




Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: artag on December 09, 2022, 03:57:26 pm
"printf" was/is a good example here, in this forum  ;D
(we tried to get rid of it, but ...)

Who did ?

I never saw anything remotely as useful and usable as printf.
Meanwhile, it's been made somewhat safer by having the compiler understand it instead as well as the runtime, though that strikes me as poor layering. Perhaps the feature itself is poorly layered too. Arguably the semantics of text formatting itself doesn't split neatly (we don't construct sentences in english hierarchicly).

There was, of course, the laughable iostream crap. A clumsy, unfunctional, hard to read, even more poorly layered and poorly laid out demonstration of operator overloading. Very much a candidate for 'we could, rather than we should, so we did'.

Any other examples ?
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Marco on December 09, 2022, 04:49:03 pm
People don't realize how much of a technological achievement Rust is.

Rust reminds me a lot of Haskell, the code hurts my head but a lot of people I can readily recognize as smarter than me are adopting it. Has more industry adoption than Haskell ever had though, even if it's mostly just taking Google's CrosVM and repurposing it.

I'm not sure the industry has enough high IQ coders to make good use of it.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 09, 2022, 05:07:31 pm
People don't realize how much of a technological achievement Rust is.

Rust reminds me a lot of Haskell, the code hurts my head but a lot of people I can readily recognize as smarter than me are adopting it. Has more industry adoption than Haskell ever had though, even if it's mostly just taking Google's CrosVM and repurposing it.

I'm not sure the industry has enough high IQ coders to make good use of it.

That latter question is extremely pertinent w.r.t. C.

If language X is safer (whatever that might mean), then arguably you can get away with X programmers having a lower "IQ".
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 05:18:09 pm
People don't realize how much of a technological achievement Rust is.

Rust reminds me a lot of Haskell, the code hurts my head but a lot of people I can readily recognize as smarter than me are adopting it. Has more industry adoption than Haskell ever had though, even if it's mostly just taking Google's CrosVM and repurposing it.

I'm not sure the industry has enough high IQ coders to make good use of it.

I've read about Rust, it was refreshing, but a few days ago I read this too (https://kevinlynagh.com/rust-zig/), the guy is clearly a seasoned MCU engineer too.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 05:36:37 pm
This in particular has now caught my attention:

Quote
Zig manages to provide many of the same features with a single mechanism - compile-time execution of regular zig code. This comes will all kinds of pros and cons, but one large and important pro is that I already know how to write regular code so it's easy for me to just write down the thing that I want to happen.

From here (https://www.scattered-thoughts.net/writing/assorted-thoughts-on-zig-and-rust/).

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: hamster_nz on December 09, 2022, 07:58:14 pm
Simple set theory says C is more than some other languages.

C gives you the ability to write a whole class of programs that are outside of what can be written in 'safe' language, or a highly managed runtime environment - those with memory leakage, smashed stacks and other "bad stuff". The set of possible programs achievable in C has to be larger than a 'safe' programming language. Most would argue that these programs sit outside of the C standards, but it is what it is.

Most of the time the overreach is not a good thing - but sometimes the ability to shoot yourself in the foot in a very controlled manner is important. Especially when directly controlling hardware, or OS HAL type work.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 08:09:14 pm
Simple set theory says C is more than some other languages.

C gives you the ability to write a whole class of programs that are outside of what can be written in 'safe' language, or a highly managed runtime environment - those with memory leakage, smashed stacks and other "bad stuff". The set of possible programs achievable in C has to be larger than a 'safe' programming language. Most would argue that these programs sit outside of the C standards, but it is what it is.

Most of the time the overreach is not a good thing - but sometimes the ability to shoot yourself in the foot in a very controlled manner is important. Especially when directly controlling hardware, or OS HAL type work.

Several people in this and related threads keep saying the language has great support for "directly controlling hardware" and "systems programming" yet I've still not seen any concrete examples of such features, features that other languages presumably don't have.

The language certainly can be used for manipulating hardware, and indeed is used for that a great deal, but that doesn't mean it is good at doing that, or has some special features designed for doing that.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 09, 2022, 08:38:48 pm
This in particular has now caught my attention:

Quote
Zig manages to provide many of the same features with a single mechanism - compile-time execution of regular zig code. This comes will all kinds of pros and cons, but one large and important pro is that I already know how to write regular code so it's easy for me to just write down the thing that I want to happen.

From here (https://www.scattered-thoughts.net/writing/assorted-thoughts-on-zig-and-rust/).

That feature is nice.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: SiliconWizard on December 09, 2022, 08:43:53 pm
A language that is both "safe", good at high-level stuff, and also very nice for low-level stuff: Ada. Anyone serious about designing programming languages should at least have a look at it IMHO.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 09:43:34 pm
A language that is both "safe", good at high-level stuff, and also very nice for low-level stuff: Ada. Anyone serious about designing programming languages should at least have a look at it IMHO.

That's a good point, I've neglected Ada, just speed-read a few articles, time for an in-depth look.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 09:49:24 pm
Regarding Ada:

Quote
One important distinction between Ada and a language like C is that statements and expressions are very clearly distinguished. In Ada, if you try to use an expression where a statement is required then your program will fail to compile. This rule supports a useful stylistic principle: expressions are intended to deliver values, not to have side effects.

Music to my ears...
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 09:50:41 pm
A language that is both "safe", good at high-level stuff, and also very nice for low-level stuff: Ada. Anyone serious about designing programming languages should at least have a look at it IMHO.

So why aren't we all using Ada for programming these microcontrollers? What's been the issue here?

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: nfmax on December 09, 2022, 10:11:07 pm
A language that is both "safe", good at high-level stuff, and also very nice for low-level stuff: Ada. Anyone serious about designing programming languages should at least have a look at it IMHO.

So why aren't we all using Ada for programming these microcontrollers? What's been the issue here?

Historically, at least, the cost of compilers. But then that used to apply to C as well
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: tggzzz on December 09, 2022, 10:22:57 pm
A language that is both "safe", good at high-level stuff, and also very nice for low-level stuff: Ada. Anyone serious about designing programming languages should at least have a look at it IMHO.

So why aren't we all using Ada for programming these microcontrollers? What's been the issue here?

In the late 70s and early 80s you bought an expensive proprietary minicomputer and expensive proprietary operating system. Some expense could be saved in an university by using Unix.

Students familiar with Unix escaped into companies, where they "bought what they knew" from companies like Microsoft (yes, their first operating system was Xenix, a Unix variant).

If you had Unix, you automatically had a free C compiler.

Ada was becoming available at the same time, but it was developed to sell to the military and priced accordingly.
Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 10:34:50 pm
Right but its free now, GNAT (https://en.wikipedia.org/wiki/GNAT)...

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Sherlock Holmes on December 09, 2022, 10:56:25 pm
OK I did some informal looking around, it seems that Ada is a can of worms. Not so much the language, but the ecosystem. It's a complex thing to setup, the tooling, editors and stuff can be costly, the language is regarded as overkill for scenarios that don't require mission critical integrity. It seems there's no straightforward, easy way to get coding in Ada for an MCU without spending thousands.

Title: Re: Should C language "undefined behaviour" cover crashing/hanging?
Post by: Mechatrommer on December 10, 2022, 01:04:56 am
Move your log experience into your thread.. remember, this thread is about how to solve division by zero in C, not ada not rust... btw machine code is dangerous! (talk about blaming technology that any language in the end all of them will be translated into)