How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc(). Note that You should free the memory only after you are done with your usage of the allocated pointers. memory allocation for 1D arrays: buffer = malloc(num_items*sizeof(double)); memory deallocation for 1D arrays: free(buffer); memory allocation for 2D … Read more

Under what circumstances can malloc return NULL?

You need to do some work in embedded systems, you’ll frequently get NULL returned there 🙂 It’s much harder to run out of memory in modern massive-address-space-and-backing-store systems but still quite possible in applications where you process large amounts of data, such as GIS or in-memory databases, or in places where your buggy code results … Read more

Does malloc() allocate a contiguous block of memory?

To answer your numbered points. Yes. All the bytes. Malloc/free doesn’t know or care about the type of the object, just the size. It is strictly speaking undefined behaviour, but a common trick supported by many implementations. See below for other alternatives. The latest C standard, ISO/IEC 9899:1999 (informally C99), allows flexible array members. An … Read more

aligned malloc() in GCC?

Since the question was asked, a new function was standardized by C11: void *aligned_alloc(size_t alignment, size_t size); and it is available in glibc (not on windows as far as I know). It takes its arguments in the same order as memalign, the reverse of Microsoft’s _aligned_malloc, and uses the same free function as usual for … Read more

Is it better to allocate memory in the power of two?

Just give the exact size you need. The only reason that a power-of-two size might be “better” is to allow quicker allocation and/or to avoid memory fragmentation. However, any non-trivial malloc implementation that concerns itself with being efficient will internally round allocations up in this way if and when it is appropriate to do so. … Read more

Malloc and constructors

Er…use new? That’s kind of the point. You can also call the constructor explicitly, but there’s little reason to do it that way Using new/delete normally: A* a = new A(); delete a; Calling the constructor/destructor explicitly (“placement new”): A* a = (A*)malloc(sizeof(A)); new (a) A(); a->~A(); free(a);

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)