malloc - Why, or when, do you need to dynamically allocate memory in C? -
dynamic memory allocation important topic in c programming. however, i've been unable find explanation of enables do, or why required.
can't declare variables , structs , never have use malloc()?
as side note, difference between:
ptr_one = (int *)malloc(sizeof(int));
and
int *ptr_one = malloc(sizeof(int));
you need use dynamic memory when:
- you cannot determine maximum amount of memory use @ compile time;
- you want allocate very large object;
- you want build data structures (containers) without fixed upper size;
you don't know how memory need set aside @ compile time. imagine processing data file (a time series of temperatures, say), number of records in file isn't fixed. have few 10 records or many 100000. if want read data memory process it, won't know how memory allocate until read file. if file structured first value number of records, this:
size_t recs = 0; double *temps = null; file *fp = fopen ( filename, "r" ); if ( fp ) { if ( fscanf( fp, "%zu", &recs ) == 1 ) { temps = malloc( sizeof *temps * recs ); if ( temps ) { // read contents of file temps } } }
sometimes need allocate very large object, like
int ginormous[1000][1000][1000];
assuming 4-byte integer, array require 4gb. unfortunately, stack frames (where local variables kept on architectures) tend smaller that, trying allocate memory may lead run-time error (and typically does). dynamic memory pool (a.k.a. heap) typically much larger stack, less 1 stack frame. obnoxious you'd need write like
int (*ginormous)[1000][1000] = malloc( sizeof *ginormous * 1000 );
it's still possible request fail; if heap fragemented enough, may not have single contiguous block large enough hande request. if necessary, piecemeal allocation; rows won't adjacent in memory, it's more you'll able grab memory need:
int ***ginormous = malloc( sizeof *ginormous * 1000 ); if ( ginormous ) { ( size_t = 0; < 1000; i++ ) { ginormous[i] = malloc( sizeof *ginormous[i] * 1000 ); if ( ginormous[i] ) { ginormous[i][j] = malloc ( sizeof *ginormous[i][j] * 1000 ); if ( ginormous[i][j] ) { // initialize ginormous[i][j][k] } } } }
and finally, dynamic memory allows build containers can grow , shrink add or remove data, such lists, trees, queues, etc. build own real "string" data type can grow append characters (similar string
type in c++).
Comments
Post a Comment