r/programminghelp • • Aug 18 '21

C++ Undefined behavior in cpp

Hey everyone,

I just start to learn cpp at my school and there is one notion I don't understand that much. Some teachers gives an function to complete and they say the function can have an undefined behavior. I read some articles and I don't understand it really well soo if anyone can help me to understand it with some exemple it would be very kind, thx guys

5 Upvotes

4 comments sorted by

View all comments

2

u/[deleted] Aug 18 '21

Take a look at the definition given here: https://en.cppreference.com/w/c/language/behavior

Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar more than once in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.

See also: https://en.cppreference.com/w/cpp/language/ub

1

u/UniqueViolinist1111 Aug 18 '21 edited Aug 18 '21

thank you for your answer but the problem is ... I'm not really good in english ( I'm french by the way), there are some parts or subtleties I don't understand ....

But is there a way to deal with those behaviors ? I don't know if I can compile a project if I for example access an index in an array wich doesn't exist ....

1

u/SaylorMan1496 Aug 18 '21

It also never hurts to just try something and when it breaks figure out why (by googling) and going from there, that is IMO the best way to learn