Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

C Tutorial

C HOMEC IntroC Get StartedC SyntaxC OutputC CommentsC VariablesC Data TypesC Type ConversionC ConstantsC OperatorsC BooleansC If...ElseC SwitchC While LoopC For LoopC Break/ContinueC ArraysC StringsC User InputC Memory AddressC Pointers

C Functions

C FunctionsC Function ParametersC ScopeC Function DeclarationC Math FunctionsC Inline FunctionsC RecursionC Function Pointers

C Files

C Create FilesC Write To FilesC Read Files

C Structures

C StructuresC Nested StructuresC Structs & PointersC UnionsC typedefC Struct Padding

C Enums

C Enums

C Memory

C Memory Management

C Errors

C ErrorsC DebuggingC NULLC Error HandlingC Input Validation

C More

C DateC Random NumbersC MacrosC Organize CodeC Storage ClassesC Bitwise OperatorsC Fixed-width Integers

C Projects

C Projects

C Reference

C ReferenceC KeywordsC <stdio.h>C <stdlib.h>C <string.h>C <math.h>C <ctype.h>C <time.h>

C Examples

C ExamplesC Real-Life ExamplesC ExercisesC QuizC CompilerC SyllabusC Study PlanC Interview Q&AC Certificate

CAllocate Memory


The process of reserving memory is called allocation. The way to allocate memory depends on the type of memory.

C has two types of memory: Static memory and dynamic memory.


Static Memory

Static memory is memory that is reserved for variablesbefore the program runs. Allocation of static memory is also known ascompile time memory allocation.

C automatically allocates memory for every variable when the program is compiled.

For example, if you create an integer array of 20 students (e.g. for a summer semester), C will reserve space for 20 elements which is typically 80 bytes of memory (20 * 4):

Example

int students[20];
printf("%zu", sizeof(students)); // 80 bytes
Try it Yourself »

But when the semester starts, it turns out that only 12 students are attending. Then you have wasted the space of 8 unused elements.

Since you are not able to change the size of the array, you are left with unnecessary reserved memory.

Note that the program will still run, and it is not damaged in any way. But if your program contains a lot of this kind of code, it may run slower than it optimally could.

If you want better control of allocated memory, take a look at Dynamic Memory below.


Dynamic Memory

Dynamic memory is memory that is allocatedafter the program starts running. Allocation of dynamic memory can also be referred to asruntime memory allocation.

Unlike with static memory, you have full control over how much memory is being used at any time. You can write code to determine how much memory you need and allocate it.

Dynamic memory does not belong to a variable, it can only be accessed with pointers.

To allocate dynamic memory, you can use themalloc() orcalloc() functions. It is necessary to include the<stdlib.h> header to use them. Themalloc() andcalloc() functions allocate some memory and return a pointer to its address.

int *ptr1 = malloc(size);
int *ptr2 = calloc(amount,size);

Themalloc() function has one parameter,size, which specifies how much memory to allocate, measured in bytes.

Thecalloc() function has two parameters:

  • amount - Specifies the amount of items to allocate
  • size - Specifies the size of each item measured in bytes

Note: The data in the memory allocated bymalloc() is unpredictable. To avoid unexpected values, make sure to write something into the memory before reading it.

Unlikemalloc(), thecalloc() function writes zeroes into all of the allocated memory. However, this makescalloc() slightly less efficient.

The best way to allocate the right amount of memory for a data type is to use thesizeof operator:

int *ptr1, *ptr2;
ptr1 = malloc(sizeof(*ptr1));
ptr2 = calloc(1, sizeof(*ptr2));

Be careful:sizeof(*ptr1) tells C to measure the size of the data at the address. If you forget the* and writesizeof(ptr1) instead, it will measure the size of the pointer itself, which is the (usually) 8 bytes that are needed to store a memory address.

Note: Thesizeof operator cannot measure how much dynamic memory is allocated. When measuring dynamic memory, it only tells you the size of thedata type of the memory. For example, if you reserve space for 5float values, thesizeof operator will return 4, which is the number of bytes needed for a singlefloat value.

Let's use dynamic memory to improve the students example above.

As noted previously, we cannot usesizeof to measure how much memory was allocated, we have to calculate that by multiplying the amount of items by the size of the data type:

Example

int *students;
int numStudents = 12;
students = calloc(numStudents, sizeof(*students));
printf("%d", numStudents * sizeof(*students)); // 48 bytes
Try it Yourself »

Notes

When working with dynamic memory allocation, you should alsocheck for errors andfree memory at the end of the program. You will learn more about this in the next chapters.


Stack Memory

For completeness, it is worth mentioning stack memory. Stack memory is a type of dynamic memory which is reserved for variables that are declared inside functions. Variables declared inside a function use stack memory rather than static memory.

When a function is called, stack memory is allocated for the variables in the function. When the function returns the stack memory is freed.

It is good to be aware of stack memory to be able to handle the memory usage of nested function calls and recursion. Recursion that repeats itself too many times may take up too much stack memory. When that happens it is called astack overflow.





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp