Behavior, guarantees aur undefined behavior
Undefined, unspecified aur documented implementation choices separate karke operation se pehle preconditions justify karein.
Is chapter mein9 sections
Ek run ka result hamesha C ki guarantee nahi batata. Kuch choices implementation document karti hai, kuch unspecified hain aur kuch operations undefined behavior dete hain. In categories se samjhenge ki kaunsa conclusion justified hai.
Ideas ko saath rakhkar samajhna hai? Concept guide kholein.
1. Teen kinds ki freedom alag samjhein
| Category | Meaning |
|---|---|
| Unspecified behavior | Multiple permitted choices; implementation ko chosen order document karna required nahi. Example: independent function arguments ka order. |
| Implementation-defined behavior | Permitted implementation choice jo documented hona chahiye. Example: plain char signedness ya negative signed value ka right shift. |
| Undefined behavior | Us execution par standard requirements impose nahi karta. Crash, rejection, warning ya consistent result promised nahi. |
Unspecified ka matlab anything-can-happen nahi. Har outcome applicable rules follow karega. Implementation-defined ka matlab experiment karke discover karna nahi; implementation documentation consult karein. Undefined behavior koi extra arithmetic result nahi jise measure karna ho. Implementation extensions document kar sakti hai, par reliance ke liye explicit implementation contract chahiye.
2. Guarantee needed hone se pehle validate karein
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
static bool read_element(const int *values, size_t count, size_t index, int *result)
{
if (values == NULL || result == NULL || index >= count) return false;
*result = values[index];
return true;
}
int main(void)
{
int values[] = { 2, 4, 6 };
int result = 99;
bool rejected = read_element(values, 3, 3, &result);
assert(!rejected && result == 99);
bool accepted = read_element(values, 3, 2, &result);
assert(accepted && result == 6);
return 0;
}
Check subscripting aur element read dono se pehle hai. Out-of-bounds read ke baad check too late hoga. Function caller par ab bhi rely karta hai: values at least count readable int elements aur result writable int designate kare. Non-null pointer aur integer count live allocation, correct type, alignment ya truthful capacity ka proof nahi.
Other violations mein signed overflow, certain indeterminate values read, lifetime ke baad object use, invalid pointer arithmetic, incompatible type access, unsequenced conflicts aur data races hain. Following lessons boundaries develop karti hain. Invalid example ko expected output assign na karein. Unit defined examples aur explicit build-rejection cases run karti hai, deliberately UB execute nahi.
3. Surprising value fully defined ho sakti hai
unsigned int value = UINT_MAX;
value += 1U;
Unsigned arithmetic maximum representable value se one more ke modulo mein reduce hoti hai. Yahan wrap defined hai. Isse allocation size ya application result correct nahi ho jaata. Defined language behavior aur application specification satisfy hona separate tests hain. Ordinary signed addition result type ki range exceed kare toh undefined behavior hai; familiar CPU wrap portable meaning nahi.
4. Required diagnostic different question hai
Syntax rule ya constraint violate karne wali translation unit standard rules ke under diagnostic require karti hai. Iska matlab har UB-triggering runtime path par diagnostic required, ya har diagnostic translation stop kare, nahi. Intentionally invalid declaration int pointer ko nonzero integer se permitted conversion ke bina initialize karti hai; checked strict build ise reject karta hai.
int *pointer = 7;
5. Tests contract ke andar evidence dete hain
Warnings, sanitizers, assertions, reviews aur different builds different defects find karte hain. Silence saari language requirements, inputs ya targets establish nahi karti. Optimization valid-program assumptions exploit kar sakti hai; optimization change useful investigation hai, UB repair nahi. Operation ki preconditions likhkar har path par preserve karein.
Primary references aur aage ki reading
- WG14 N1570 — public C11 committee draft: 3.4, 5.1.1.3, 6.2.5p9, 6.5, 6.7.9. C17 baseline ke stable core rules ke liye; final ISO publication nahi.
- WG14 N3096 — public C23 working draft: 6.2.6.2, 6.5. C23 notes C17 example checks se separately source-reviewed hain.
Valid explanation ke liye operation bhi valid hona chahiye
Idea compare karein, follow karein aur samjhayein
Undefined behavior mein us situation ke liye C standard koi requirements impose nahi karta. Iska matlab surprising output guess karna nahi hai. Pehle poochhein ki har evaluated operation apna contract satisfy karta hai ya nahi.
Yeh kab kaam aata hai Bounds, expired objects, arithmetic limits aur interacting side effects wale expressions trace karne se pehle yeh habit use karein.
Ideas ko saath rakhkar padhein
- Unspecified behavior
- Standard alternatives allow karta hai; implementation ko chosen alternative document karna required nahi.
- Implementation-defined behavior
- Allowed choice ko implementation document karta hai.
Dono ki language-defined boundaries hain; dono ka matlab har possible outcome nahi.
- Undefined behavior
- Affected situation par standard koi requirements impose nahi karta.
- Constraint violation
- Translation unit mein constraint violate hoti hai. Conforming implementation ko us unit ke liye kam se kam ek diagnostic dena hota hai.
Diagnostic ka matlab compile karne se refusal zaroori nahi; har undefined operation par diagnostic required nahi.
- Successful observed run
- Ek build aur environment mein ek run ka observation hai.
- Language guarantee
- Stated C rules aur preconditions ke under apply hoti hai.
Sirf observation se program ka defined behavior prove nahi hota.
Reasoning ko follow karein
Subscripted read se pehle bounds check karein. Example jaanboojhkar one-past index choose karke safe alternative leta hai.
C17 · diye gaye context ke illustrative fragments
int values[3] = {3, 6, 9};size_t index = 3;if (index < 3) {/* values[index] may be read here */} else {/* handle the missing element */}
- Valid indexes samjhein
Three-element array ke indexes 0, 1 aur 2 hain.
- index ki value padhein
index mein 3 hai. Sirf is integer value ko rakhna invalid array access nahi hai.
- Guard evaluate karein
index < 3 false hai. Abhi tak koi element read karne ke liye array subscript evaluate nahi hua.
- Element access skip karein
Guarded branch execute nahi hoti. Program values[3] read nahi karta.
- Missing element handle karein
else branch no element report karti hai. Out-of-range read par depend karne ke bajay is case ko defined behavior milta hai.
Common misconceptions
Yeh statements misleading hain. Kyun, yeh samajhne ke liye har statement kholein.
MisconceptionUndefined behavior mein program usi line par crash karega.
Standard kisi specific symptom ya failure point ka promise nahi karta. Build kaam karta dikh sakta hai, fail ho sakta hai ya optimization ke baad alag behave kar sakta hai.
MisconceptionTwo’s complement signed wraparound guarantee karta hai.
Representation rule overflowing signed arithmetic define nahi karta. Signed result type ki range ke bahar ja sakta ho to compute karne se pehle check karein.
MisconceptionSanitizer prove karta hai ki poore program mein undefined behavior nahi.
Sanitizer executed paths par supported conditions check karta hai. Tests aur diagnostics madad karte hain, par har path aur language rule cover nahi karte.
Thoda aur depth meinOptional technical detail
Precedence evaluation order establish nahi karta
Parentheses expression ko group karte hain. Woh generally operands ko sequence nahi karte. i++ + i++ ko unsequenced side-effect conflict ke roop mein analyze karein; portable answer dhoondhne ke liye run na karein.
Invalid operation rokein, sirf visible result nahi
Guard ko dangerous access ya arithmetic se pehle evaluate hona chahiye. Pehle values[index] read karke baad mein index check karna boundary cross kar chuka hai.
C17 Yeh bounds aur sequencing rules C17 baseline par apply hote hain. Runtime undefined behavior aur translation-time constraint diagnostics ka difference rakhein.
C23 C23 out-of-bounds reads, expired objects ka access ya unsequenced modifications ko safe nahi banata. Two’s-complement representation se signed arithmetic overflow defined nahi hota.
Yeh public committee drafts hain; clause references se explanation verify kar sakte hain. N3096 ek C23 working draft hai.
Apne words mein samjhayein
Is three-element array ke liye sirf index = 3 store karna undefined hai?
Ek explanation se compare karein
Nahi. Integer value store aur test kar sakte hain. Guarded example invalid element access avoid karta hai, isliye us value ko safely handle kar sakta hai.
Aage badhne se pehle
- Undefined, unspecified aur implementation-defined behavior different language categories hain.
- Language-valid operation application requirements tod sakta hai.
- Ek observed result language ki absent guarantee establish nahi karta.
In ideas ko alag rakhein
- Undefined / Unspecified
- Undefined behavior mein standard us execution ke requirements nahi deta; unspecified behavior allowed possibilities ki choice deta hai.
Do observed outputs allowed choice hain ya invalid operation, yeh kaise decide karenge?
Optional: bolkar samjhein ya note rakhein. Tayyar hon toh aage badh sakte hain.Apni understanding check karein
Optional hai. Answers save ya send nahi hote; chapter kabhi lock nahi hota.
Har choice ki explanation padhein
- Ki operation portable hai.
Ek observed outcome language guarantee nahi bana sakta.
- Sirf ki is run mein yeh observation mila.
✓ Sahi reasoning. Undefined behavior ke liye C standard requirements impose nahi karta; sahi dikhta run operation validate nahi karta.
- Ki compiler ko har baar warning deni hogi.
Har possible undefined behavior ke liye diagnostic required nahi.
C17
Earlier edition ka quick reference
Existing section links aur saved passages ke liye retained. Connected ideas expanded lessons mein hain; exact corrections source review mein recorded hain.
Yeh teen categories, C standard dwara precisely define ki gayi hain, un situations describe karti hain jahan standard yeh fully pin down nahi karta ki kya hoga — aur inhe confuse karna ek common source hai un bugs ka jo ek compiler par "work" karte hain aur doosre par fail ho jaate hain.
- Undefined behavior (UB). Standard execution par requirements impose nahi karta. Examples: invalid pointer dereference, signed integer overflow, indeterminate automatic
intka use, out-of-bounds element access, scalar object par unsequenced conflicting accesses, ya data race. Crash ya diagnostic guaranteed nahi. - Unspecified behavior. Standard ek se zyada outcomes allow karta hai aur implementation ko yeh document karne ki requirement nahi deta ki usne kaunsa choose kiya — jaise, ek function ke arguments kis order mein evaluate honge.
- Implementation-defined behavior. Unspecified behavior jaisa hi, sirf implementation ko apna choice document karna zaroori hai — jaise,
intaurlongka exact size, plaincharsigned hai ya nahi, aur ek negative number ko right-shift karne ka result.
Practical stakes portability aur correctness hain: code jo undefined behavior par rely karta hai, developer ki apni machine par har test pass kar sakta hai, phir bhi ek different compiler, optimization level, ya hardware architecture par unpredictably fail ho sakta hai — isi wajah se compiler warnings, sanitizers, aur static analyzers (Section 32) ko serious C development mein optional extras ke bajaye essential tools maana jaata hai.
Agla idea padhne ke liye tayyar?
Mark this chapter as read whenever you feel ready.