A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
18
Task/Memory-allocation/C/memory-allocation-1.c
Normal file
18
Task/Memory-allocation/C/memory-allocation-1.c
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
/* size of "members", in bytes */
|
||||
#define SIZEOF_MEMB (sizeof(int))
|
||||
#define NMEMB 100
|
||||
|
||||
int main()
|
||||
{
|
||||
int *ints = malloc(SIZEOF_MEMB*NMEMB);
|
||||
/* realloc can be used to increase or decrease an already
|
||||
allocated memory (same as malloc if ints is NULL) */
|
||||
ints = realloc(ints, sizeof(int)*(NMEMB+1));
|
||||
/* calloc set the memory to 0s */
|
||||
int *int2 = calloc(NMEMB, SIZEOF_MEMB);
|
||||
/* all use the same free */
|
||||
free(ints); free(int2);
|
||||
return 0;
|
||||
}
|
||||
17
Task/Memory-allocation/C/memory-allocation-2.c
Normal file
17
Task/Memory-allocation/C/memory-allocation-2.c
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
int func()
|
||||
{
|
||||
int ints[NMEMB]; /* it resembles malloc ... */
|
||||
int *int2; /* here the only thing allocated on the stack is a pointer */
|
||||
char intstack[SIZEOF_MEMB*NMEMB]; /* to show resemblance to malloc */
|
||||
int2 = (int *)intstack; /* but this is educative, do not do so unless... */
|
||||
|
||||
{
|
||||
const char *pointers_to_char[NMEMB];
|
||||
/* use pointers_to_char */
|
||||
pointers_to_char[0] = "educative";
|
||||
} /* outside the block, the variable "disappears" */
|
||||
|
||||
/* here we can use ints, int2, intstack vars, which are not seen elsewhere of course */
|
||||
|
||||
return 0;
|
||||
}
|
||||
8
Task/Memory-allocation/C/memory-allocation-3.c
Normal file
8
Task/Memory-allocation/C/memory-allocation-3.c
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#include <alloca.h>
|
||||
int *funcA()
|
||||
{
|
||||
int *ints = alloca(SIZEOF_MEMB*NMEMB);
|
||||
ints[0] = 0; /* use it */
|
||||
return ints; /* BUT THIS IS WRONG! It is not like malloc: the memory
|
||||
does not "survive"! */
|
||||
}
|
||||
14
Task/Memory-allocation/C/memory-allocation-4.c
Normal file
14
Task/Memory-allocation/C/memory-allocation-4.c
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
/* this is global */
|
||||
int integers[NMEMB]; /* should be initialized with 0s */
|
||||
|
||||
int funcB()
|
||||
{
|
||||
static int ints[NMEMB]; /* this is "static", i.e. the memory "survive" even
|
||||
when the function exits, but the symbol's scope is local */
|
||||
return integers[0] + ints[0];
|
||||
}
|
||||
|
||||
void funcC(int a)
|
||||
{
|
||||
integers[0] = a;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue