نطاقات
المتغيرات
أفعال

malloc

من cppreference.com
< c | memory
<tbody> </tbody>
معرفة في ملف <stdlib.h>
void* malloc( size_t size );

تحجز مساحة في الذاكرة مقدرها ‎size‎ بايت. هذه المساحة ذات قيمة عشوائية. عند نجاح الحجز، ترجع هذه الدالة مؤشرًا إلى البايت الأول من المساحة المحجوزة. أما إذا كانت ‎size‎ صفرًا، سيختلف سلوك الدالة بختلاف البيئة (فربما ترجع قيمة مكافئة لـ ‎NULL‎، أو ترجع مؤشرًا إلى منطقة لا يجوز استخدامها).

‎malloc‎ is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.

A previous call to free‎ or realloc‎ that deallocates a region of memory synchronizes-with a call to malloc‎ that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by ‎malloc‎

(منذ C11)

المعطيات

size - عدد البايتات المراد حجزها

القيمة المُرجعة

عند نجاح العملية ترجع مؤشرًا يؤشر إلى بداية الجزء الذي حجز في الذاكرة أو مؤشرًا مكافئًا لـ ‎NULL‎ عند حدوث خطأ. لتحرير المساحة المحجوزة في الذاكرة؛ ليستخدمها النظام من جديد، يجب استعمال الدالة free()‎.

مثال

#include <stdio.h>   
#include <stdlib.h> 

int main(void) 
{
    /* حجز مساحة لمصفوفة مكونة من 4 عناصر int */
    int *pa = malloc(4*sizeof(int));
    if (pa == NULL) {
       printf("malloc() failed in file %s at line # %d", __FILE__,__LINE__);
       exit(1);
    }
    
    /* تمهيد المصفوفة بقيم */
    for (int ndx=0; ndx < 4; ndx++)
        pa[ndx] = ndx;

    /* طبعا أحد العناصر */
    printf("pa[3] = %d\n", pa[3]);
    
    /* اخلاء المساحة المحجوزة واعادتها إلى النظام */
    free(pa);
    return 0;
}

الخرج:

pa[3] = 3

أنظر أيضا