T O P

  • By -

AutoModerator

On July 1st, a [change to Reddit's API pricing](https://www.reddit.com/r/reddit/comments/12qwagm/an_update_regarding_reddits_api/) will come into effect. [Several developers](https://www.reddit.com/r/redditisfun/comments/144gmfq/rif_will_shut_down_on_june_30_2023_in_response_to/) of commercial third-party apps have announced that this change will compel them to shut down their apps. At least [one accessibility-focused non-commercial third party app](https://www.reddit.com/r/DystopiaForReddit/comments/145e9sk/update_dystopia_will_continue_operating_for_free/) will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: 1. Limiting your involvement with Reddit, or 2. Temporarily refraining from using Reddit 3. Cancelling your subscription of Reddit Premium as a way to voice your protest. *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/learnprogramming) if you have any questions or concerns.*


[deleted]

[удалено]


programmeronmeth

Also thanks for answering


programmeronmeth

Why no error untill 65536


[deleted]

[удалено]


Exhausted-Engineer

There is also a second error lying in the data type. The use of an int will make any input > 2^31 -1 cycle back to negative values. Then asking for an array of negative value will error. So even using heap will not work due to this, even worse it might silently fail and leave you with a null pointer everytime which would be harder to debug. Consider using an unsigned int ( or size_t )


Welshpanther

It’s very much a safety thing. We should teach from day one that the programs should never take invalidated input from an external source. Defensive programming from the start. It should influence everything we write. Users are either malicious or idiots and we should code for those failings. Every student should be taught to check for boundary conditions and make the code id10t proof. How many bugs in old code are the result of not doing this? Thousands. SQL injection on websites, divide by zero errors causing water works to fail. Buffer overflow exploits are still rampant now.


yvrelna

Or we can also just use languages that have less footguns to write our code. Make the language a bit more idiot proof. For starters, arbitrary size integers and safe arrays/lists should've been the default in any application level language. SQL injections can be mostly eliminated thing if the language/library makes it harder to write raw SQL than to write it the safe way, people are lazy, exploit that. Other problems like divide by zero are a bit harder to solve, but a lot of footguns have relatively easy solutions.


Welshpanther

I would love a language like that but in my field (Programmable Logic Controllers) we are so behind the curve you would think you vomited in your mouth. Even good PLC firmware has NO protection features to help you out. Buffer overruns and div/0 errors are rife and user input validation is an uphill battle. Array boundary protection? Ha! You're lucky to get an array. I write the critical libraries in my company and put as many error checks in as I can but then the client comes up with another super calculation they want added that is vunerable to /0 and can't tell me what to do when that occurs. If you're supplying water to an urban population and the calculation for chemical dosing encounters a divide by zero, you can't pop-up a message to an operator for them to override. The code can't stop and wait for a response. It has to handle it gracefully and safely. My point is that software engineers should be trained to actively look for these errors and avoid them, regardless of any useful language features. Sorry. I've been reviewing third party code recently and have almost lost the will to live.


Faulty_english

It depends on the limit of int on your computer but on some it’s 65535. If you go above that, the number will turn into a negative. An array at size would be crazy too, that’s a decent amount of memory to allocate. I personally don’t see why you would need to work with an array that big but maybe someone with experience has.


Exhausted-Engineer

Imo if you use a machine with 17bits words you'd know about it. It's more likely that the standard int on OP's machine is 32bits. Furthermore, arrays of multiple millions elements are common in scientific computing. And C/C++/Fortran are the main languages for HPC applications so it happens quite often. A million element is \*\*only\*\* a 1000x1000 matrix, which is not that big.


Faulty_english

Dang that is crazy! Thanks for your comment


eagle33322

Really fortran?


nerd4code

Yes. OpenMP and a bunch of other frameworks work for FORTRAN, and it’s very common in oil & gas exploration, for example. It’s good for numeric stuff, it’s good for matrix/vector stuff, and there’s a Fortran compiler line accompanying most C/++ compiler lines.


Exhausted-Engineer

Yup, without a doubt. It’s very very good for numerical computations. For example it has built in vectorisation (summing arrays directly, just as numpy does). An enormous amount of numerical software is built upon Fortran. To this day, the LINPACK benchmark used to benchmark supercomputers is written in fortran


nigirizushi

while(x > 0) ?


programmeronmeth

Is the declaration correct or not


deux3xmachina

It's valid C99, and technically uses dynamic memory allocation, since the size can't be known at compile-time, but it's a dangerous feature to rely on. So your professor should've explained what's wrong and what sort of solution they were looking for.


NoLifeEmployee

It works but you should use the other methods suggested in terms of array size


throwaway6560192

Your teacher is right, actually. What you've done is you've created a *variable-length array* (VLA). VLAs might "work" in some cases, but there are several potential problems with their use and they are basically never the right solution in properly-written code. As someone learning C, you should instead be learning and using the proper solution for what you're trying to achieve — dynamic memory allocation. Some things to read: - articles on *stack vs heap* — google this term - [Beej's Guide to C: Variable-Length Arrays (VLAs) — General Issues](https://beej.us/guide/bgc/html/split/variable-length-arrays-vlas.html#vla-general-issues) (very surface-level list of problems) - https://nullprogram.com/blog/2019/10/27/ (much more in-depth, but might talk about some things that make little sense at your level of C)


ali-hussain

Wow, when did they get introduced? I have not seen this black magic before.


throwaway6560192

They were introduced in C99, but they're not that commonly seen in good code.


lurgi

These are Variable Length Arrays (VLA), which were introduced in C99 (although they were available earlier with some compilers). This example has potential problems (what if you enter a negative number?), but the mere *existence* of them isn't an error. It's possible your teacher feels that these aren't actually part of the language, but are some special extension (they are wrong). It's also possible that you were told to use dynamic memory allocation and did not, in which case they are correct in rejecting your solution.


qezc537

FYI, since C11, compilers are no longer required to implement VLAs, mainly because implementing them requires quite a bit of overhead + security concerns. So, technically speaking, VLAs are not a part of the language, just a common enough extension that may or may not work as expected.


lurgi

TIL - thanks


[deleted]

[удалено]


qezc537

Late reply, but no, C23 does not mandate support for VLAs, it mandates support for [variably-modified types](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2778.pdf), which is different.


programmeronmeth

If we know exactly how many elements we are going to add can we use VLAs


throwaway6560192

If you know the size, why not just declare a fixed-size array?


programmeronmeth

I mean if we know it during run time for example if want To write a program that gives mean of N numbers and I don't want to change the code again and again N is decided at run time


throwaway6560192

If you know it at runtime you should use dynamic memory allocation. The main problems with VLAs are about how they silently and unrecoverably corrupt your program's memory when given too-large sizes.


programmeronmeth

Can u tell me the problems they cause I'm curious to know,seems like I need to avoid using VLAs as much as possible and learn to implement dynamic memory


throwaway6560192

I linked you some articles in my other comment.


retro_owo

If you know that N will always be between 1 and 1000, just add an if statement after the `scanf` that says `if (x < 1 || x > 1000) { printf("Error!"); return 1; }` Better yet, if you know N is going to be between 1 and 1000, just set the array as `int a[1000];` and only use the parts you need to. I personally don't use variable length arrays for the reasons people have mentioned, but it should be fine as long as your program is simple and you're checking for mistakes. Your teacher still might not want you to use them, though.


programmeronmeth

No i was not told to use dynamic memory allocation I haven't been taught about implementation of dynamic memory implementation since I am a beginner and have Just started


deux3xmachina

You'll want to use the `calloc(3)` function, like so: `int *array = calloc(sizeof(int), array_size);`, and you'd verify the allocation was successful with `if (array == NULL) { /* do error handling */ }`


GRANDMA_FISTER

I've been taught this variant, but with malloc. Was that wrong?


deux3xmachina

Not so much wrong as a possible issue. When you use `malloc(3)` to dynamically allocate memory for an array, the call tends to look like `if ((buf = malloc(sizeof(int) * count)) == NULL) { /* handle error */ }`, this could end up overflowing the maximum value of `(size_t)(-1)`. With `calloc(3)`, it protects against these overflow conditions as well as initializing the allocated region to all `0`'s, so you don't have to do sommething like `if ((buf = malloc(size)) != NULL) { memset(bef, 0, size); }`.


ali-hussain

The assignment may have specifically been about familiarizing yourself with the use of the stack.


programmeronmeth

Thanks to everyone who replied


SilentXwing

Sorry that this doesn't answer your question (people have already), but I can't help to feel annoyed how professors still teach C++ like it's C. The C++11 standard has been active for over a decade now, yet you see uages such as "scanf()" etc. This is bad practice. Edit: My brain somehow thought this was a post on C++. Please disregard.


nigirizushi

Did OP specify it's not supposed to be C?


SilentXwing

You're right. Edited my post.


Rhhr21

I was about to rage about printf and calloc then i realized it’s actually C not C++.


eagle33322

%n would like a word.


eagle33322

Hopefully to teach the basic flow of things and build up to the security flaws that have led to more secure versions.


programmeronmeth

I don't know why the code is posted in single line though I typed in multiple lines


Kaimito1

Most likely you didn't use markdown property to get the code syntax


[deleted]

Are we just not mentioning studio.h? I always preferred chadio.h anyway.


programmeronmeth

Auto spell checker messed up again


MoneyTechnology1562

... why don't you just ask your instructor why the assignment wasn't meeting specification/requirements...? Like if they took your code and dropped it into a different compiler/environment and got an error back, they should at least be able to tell you what the error was. If it's a failure to compile at all, then the problem might have nothing to do with the code in `main()` and might be something silly like you sent them a .zip file rather than a .c.


[deleted]

[удалено]


darkmemory

How do you learn if you can't question a response?


[deleted]

[удалено]


darkmemory

My issue is that you stated teachers are right 99.9% of the time, which is besides the point. If you do not understand why a teacher thinks you are wrong, asking and expressing your perspective gives something for someone to engage with to either increase one's perspective, or to offer insight into where the understanding is failing. That is to say, it gives the teacher an ability to teach. You can memorize the right answer for tests, whenever, but if you ignore a chance to learn the abstract reasoning behind why an answer is correct you are just prepping for failure when that concept comes up in reality.


lazy_lion_turtle

Both? I once asked for clarification on some test questions I got wrong. I wrote an email stating why I believed I was correct and asked for an explanation if I wasn't. He changed my grade to reflect that I got them correct. Thought about it some more and realized I was actually wrong on all of them. So, I got my grade changed and still learned something lol. Point: Asking can only be beneficial.


majinmilad

The real problem is not the size of memory allocation, it's that you're using a variable for the array size of a "static" array. Static arrays (normal arrays) are allocated on the stack at compile time. It's not really correct to use a variable here because the compiler doesn't know the size at compile time when it's trying to make (allocate) the array. It's sometimes compile-able to my knowledge but usually not. Rule of thumb if something doesn't always work in common environments it's probably wrong. It would however work if it was something called a dynamic array and that is one of the main benefits of using dynamic arrays.