YOUR C LEARNING COMPANION

Kahan se padhein?

Learning path
Memory aur dataChapter 28 of 73

Dynamic memory aur ownership

Allocation, initialization, size checks, replacement aur release ko deliberate ownership contract se jodein.

7 min readFoundationsC17 baseline
Offline reading
Is chapter mein9 sections
0% through this chapter

Kabhi required storage size program chalne par hi pata chalta hai. Allocation us storage ki request karta hai; ownership batati hai ki use release kaun karega. Hum success ke saath request fail hone ka path bhi follow karenge.

1. Allocation alag lifetime control karti hai

malloc, calloc, realloc aur free, <stdlib.h> mein declared hain. Inke rules allocated storage control karte hain. Local pointer disappear hone se allocation automatically end nahi hoti; allocation free ho sakti hai jabki pointer object exist karta rahe. Pointer aur allocation ki ek shared lifetime nahi hai.

  1. Storage request
  2. Result check
  3. Initialize aur use
  4. Ek baar release
Ownership program ki management convention hai, naya C type ya raw pointer ki carried guarantee nahi.
C17 · illustrative fragment
int *value = malloc(sizeof *value);
if (value == NULL) {
    return EXIT_FAILURE;
}
*value = 4;
assert(*value == 4);
free(value);
value = NULL;

Is non-VLA target type ke liye sizeof *value required size pointer dereference kiye bina deta hai. Allocation access karne se pehle result check karein. C mein returned void * suitable object pointer mein bina cast convert hota hai. malloc allocated bytes initialize nahi karta; yahan assignment usable int value deta hai.

2. Size ka meaning bina lose kiye calculate karein

SIZE_MAX, <stdint.h> se milta hai; size-limit check ke liye yeh header include karein. Fragments initialized values ke checks ke liye <assert.h> ka assert bhi use karte hain.

C17 · illustrative fragment
size_t count = 3;
int *values = NULL;
if (count == 0 || count > SIZE_MAX / sizeof *values) {
    return EXIT_FAILURE;
}
values = malloc(count * sizeof *values);
if (values == NULL) {
    return EXIT_FAILURE;
}
values[0] = 4;
values[1] = 5;
values[2] = 6;
assert(values[2] == 6);
free(values);

Interface jaan-bujhkar zero count reject karta hai. Division check multiplication se pehle hota hai, taaki count * sizeof *values, size_t mein wrap na ho. Wrapped small result element count ke liye insufficient space allocate kar sakta hai. sizeof *values intended element type use karta hai; sizeof values pointer size dega.

Successful ordinary allocation fundamental alignment requirements wale types ke liye suitable alignment deti hai. Isko har extended ya specially aligned type tak generalize na karein. Cast ko initialization na samjhein: access ko alignment aur bina declared type wali storage ke effective-type rules follow karne hote hain. Yeh lesson correctly typed pointers se written ordinary integers use karta hai.

3. calloc zero bits promise karta hai

C17 · illustrative fragment
int *values = calloc(3, sizeof *values);
if (values == NULL) {
    return EXIT_FAILURE;
}
assert(values[0] == 0);
assert(values[2] == 0);
free(values);

calloc element count aur element size separately leta hai aur allocated space ke bits zero set karta hai. Is example ke integer objects mein woh integer zero represent karta hai. Arbitrary allocated objects mein null pointer values ya floating-point zero values universally establish nahi hoti. Byte zeroing aur language-level initialization related lekin alag operations hain.

4. Successful realloc allocation replace karta hai

Complete C17 program
#include <assert.h>
#include <stdlib.h>

int main(void)
{
    int *values = malloc(2 * sizeof *values);
    if (values == NULL) {
        return EXIT_FAILURE;
    }
    values[0] = 4;
    values[1] = 5;

    int *replacement = realloc(values, 3 * sizeof *values);
    if (replacement == NULL) {
        free(values);
        return EXIT_FAILURE;
    }
    values = replacement;
    values[2] = 6;
    assert(values[0] == 4 && values[1] == 5);
    assert(values[2] == 6);
    free(values);
    return 0;
}

Valid old allocation aur nonzero requested size mein failure null pointer return karta hai aur old allocation available rehti hai. Result temporary mein rakhne se failure par owning pointer preserve rehta hai. Success par old allocation deallocate hoti hai aur returned pointer replacement designate karta hai, jo apparent same address par bhi ho sakti hai. Old object ke saare old pointers use karna band karein; old pointer ko result se compare na karein.

Existing contents old aur new size ke smaller portion tak preserve hote hain. Newly added storage automatically initialize nahi hoti. Example new third element read karne se pehle assign karta hai. Replacement ke baad needed interior pointers returned pointer aur valid offsets se rebuild karein; stale aliases carry forward na karein.

5. Ownership aapka maintained contract hai

Ownership identify karta hai ki release ki responsibility program ke kis part ki hai. Borrowed pointer contract ki permission tak object access kar sakta hai; raw C pointer yeh distinction record ya enforce nahi karta. Owner ka pointer copy karne se do allocations nahi banti, na dono copies free karne ki permission milti hai. Ek allocation valid deallocation path se at most ek baar release honi chahiye.

free(NULL) kuch nahi karta. Otherwise deallocator ke liye accepted valid allocation pointer pass karein; interior pointer, automatic array, string literal ya already released value nahi. Free karna operating system ko physical pages immediately return karna require nahi karta. Leak unreleased storage ki management failure hai, kisi particular heap diagram ka ek direction mein grow karne ka promise nahi.

Primary references aur aage padhne ke liye

  • WG14 N1570 — public C11 committee draft: 6.2.4, 6.5p6–p7, 7.22.3 (stable allocation rules). Yeh stable rules C17 baseline ko support karte hain; yeh draft final ISO publication nahi hai.
  • WG14 N3096 — public C23 draft: 7.24.3.7, especially the separate null and non-null first-argument branches. Draft wording; implementation support separately check karein.

WG14 N2438: C17 ke zero-size realloc wording aur ambiguity ko document karta hai; yeh committee issue paper hai, final C23 rule nahi.

Optional visual model: Allocation resize aur release karein

Allocation resize aur release karein

VISUAL MODEL

Positive-size realloc ki dono outcomes dekhein. Owning pointer aur temporary result ko follow karein.

Function definition se pehle <stdlib.h> include karein. Fragment void function ke andar chalega. Pehla malloc successful maana hai. realloc outcome teaching scenario hai, real allocator control nahi.

  1. int *p = malloc(2 * sizeof *p);
  2. if (p == NULL) return;
  3. p[0] = 4; p[1] = 8;
  4. int *tmp = realloc(p, 3 * sizeof *p);
  5. if (tmp != NULL) {
  6. p = tmp;
  7. p[2] = 12;
  8. }
  9. free(p);
  10. p = NULL; tmp = NULL;
int *p—Initializer tak nahi pahunche
int *tmp—Initializer tak nahi pahunche
int[]B (allocation)—Abhi allocation nahi

Abhi allocation request nahi hui. Dono pointer initializers tak nahi pahunche.

A aur B logical allocation labels hain, addresses nahi. ? ka matlab value read nahi karni. Successful realloc purani allocation ki lifetime end karta hai, chahe implementation address reuse kare. Sirf positive sizes use hoti hain.

Poora trace padhein
  1. Abhi allocation request nahi hui. Dono pointer initializers tak nahi pahunche.
  2. malloc successful hai aur p allocation A own karta hai, jismein do int objects ki jagah hai. Unki values initialized nahi hain.
  3. Dono int values 4 aur 8 ho jaati hain. Requested allocation size, sizeof *p se express ki gayi thi.
  4. realloc successful hai. tmp allocation B ko refer karta hai; pehli do values preserved hain. Purani allocation end ho chuki, isliye p ki purani value read nahi karni.
  5. p ko tmp milta hai: unusable purani value ko read kiye bina replace kiya jaata hai. Ab p, B own karta hai; tmp alias hai.
  6. p[2] ko 12 milta hai. Ab B ki teeno int values initialized hain.
  7. free live allocation ko ek baar release karta hai. Use refer karne wali pointer values baad mein read nahi karni. Released storage se koi value read nahi hoti.
  8. Dono pointer objects ko NULL assign hota hai. Yeh purani values replace karta hai; koi extra allocation release nahi hoti.

Aage badhne se pehle

  • Allocation runtime par chosen size ka region request karta hai.
  • Program ko size arithmetic validate, failure handle aur usable values establish karni hain.
  • Ownership aur borrowing rules release aur aliases ki validity decide karte hain.
In ideas ko alag rakhein
Allocated bytes / Initialised values
Storage milne se har intended typed value initialise ya har access contract establish nahi hota.
Apne words mein samjhaayein

Resize fail ho toh original pointer available rakhte hue allocation replace kaise 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.

Positive requested size ke liye realloc NULL return karta hai. Kya valid rehta hai?
Har choice ki explanation padhein
  1. Purani allocation hamesha free ho chuki hoti hai.

    Is positive-size failure mein old allocation deallocate nahi hoti.

  2. Naya teesra element use karne ke liye ready hai.

    Failed growth request ne extra space nahi banayi.

  3. Original allocation, preserved owning pointer se reachable.

    ✓ Sahi reasoning. Temporary result use karein taaki failed call original allocation access aur release karne wala pointer overwrite na kare.

C17

Earlier edition ka quick reference

Existing section links aur saved passages ke liye retained. Connected learning sequence ke liye upar expanded explanation padhein.

Allocated storage, jise often heap memory kehte hain, <stdlib.h> functions se milti hai aur unke rules ke according release/replace hone tak allocated rehti hai. Automatic objects ki lifetimes scopes manage karte hain. Yeh language lifetime categories hain, particular physical stack aur heap regions ki requirement nahi.

Function Behavior
malloc(size) size bytes indeterminate contents ke saath allocate; NULL check karein. Zero-size requests avoid karein.
calloc(n, size) Har ek size bytes ke n elements ki space allocate karke saare bits zero karta hai. Isse null-pointer ya floating-zero representation guaranteed nahi.
realloc(ptr, size) Nonzero size par allocation resize; failure par NULL aur old allocation valid. Success par old allocation invalidate, chahe address unchanged ho.
free(ptr) Valid, abhi tak free na hue allocation ko release; free(NULL) kuch nahi karta.

Common Mistakes

  • Memory leaks — zaroorat khatam hone ke baad bhi storage allocated rehna; last usable pointer khona ek common cause hai. Process exit par storage reclaim karna operating-system behavior hai, C language ki guarantee nahi.
  • Dangling pointer / use-after-free — memory ko usse free hone ke baad bhi pointer ke through access karna.
  • Double free: Same allocation do baar free karna, ya interior/unrelated pointer free karna, undefined behavior hai. Implementation koi particular crash ya allocator diagnostic promise nahi karti.
  • realloc fail hone par original pointer khona — ptr = realloc(ptr, newSize); likhna failure par ptr ko NULL se overwrite kar deta hai aur silently original block leak ho jaata hai. Safe pattern ek temporary variable use karta hai: void *tmp = realloc(ptr, newSize); if (tmp) ptr = tmp;.

Use se pehle har allocation result aur n * sizeof *p jaise size expressions se pehle overflow check karein. Successful realloc old allocation replace karta hai; failed nonzero-size request usko available rakhti hai, isliye temporary pointer use karein. Valid non-null allocation pointer p ke liye realloc(p, 0) avoid karein: C17 ka implementation-defined behavior old block release kar sakta hai, jabki C23 mein yeh case undefined behavior hai. realloc(NULL, size), zero-size rules samet, malloc(size) jaisa behave karta hai. Requested size zero ho toh explicitly free(p) use karein. Ownership end hone par allocations release karein aur stale aliases use na karein; successful realloc ke baad old block ko separately free nahi karna. Tools leaks aur invalid accesses detect karne mein help karte hain.

Agla idea padhne ke liye tayyar?

Mark this chapter as read whenever you feel ready.

CHAPTER 28 / 73

Is chapter mein

Dynamic memory aur ownership

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping