[Info-vax] ChatGPT solved it for me, again...

Simon Clubley clubley at remove_me.eisner.decus.org-Earth.UFP
Fri Feb 17 08:20:16 EST 2023


On 2023-02-17, Slo <slovuj at gmail.com> wrote:
> Sorry Arne, I don't trust your coding skills and an ancient language :-)

That ancient language is more secure than C. :-)

> Me: Convert this code to C
>============================
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <time.h>
> int get_wattage(char *sys) {
>     return (rand() % 20) * 50 + 200;
> }
> int main() {
>     char sys1[256], sys2[256];
>     int watt1, watt2;
>     srand(time(NULL));
>     printf("Utility to check power supply compatibility.\n");
>     printf("Enter name of system #1: ");
>     fgets(sys1, 256, stdin);
>     printf("Enter name of system #2: ");
>     fgets(sys2, 256, stdin);
>     sys1[strcspn(sys1, "\n")] = '\0';
>     sys2[strcspn(sys2, "\n")] = '\0';

OUCH! OUCH! OUCH!!!!!

fgets() is not guaranteed to return a newline character.

Here's an online man page that confirms this:

https://linux.die.net/man/3/fgets

I hope people using this technology with "real" code understand and
recognise this kind of thing...

>     watt1 = get_wattage(sys1);
>     watt2 = get_wattage(sys2);
>     if (watt1 == watt2) {
>         printf("%s and %s can use the same power supply (%d watt)\n", sys1, sys2, watt1);
>     } else {
>         printf("%s and %s cannot use the same power supply as they use %d and %d watt\n", sys1, sys2, watt1, watt2);
>     }
>     return 0;
> }
>============================
> I did not test it. It also gave these comments:
>
> Note that the pstr type from the original Pascal code has been replaced with C-style strings 
> (null-terminated arrays of characters), and the random function has been replaced with the 
> rand function from the C standard library. The clock function from the original Pascal code 
> has been replaced with the time function from the C standard library to seed the random 
> number generator. The trunc function from Pascal has not been used in the C code, as C 
> automatically truncates floating-point values when they are cast to integers.


-- 
Simon Clubley, clubley at remove_me.eisner.decus.org-Earth.UFP
Walking destinations on a map are further away than they appear.



More information about the Info-vax mailing list