The main difference when writing
char* buf;
is that it is uninitialized and no memory is allocated, so you'll have to take care yourself:
char* buf = malloc(10 * sizeof(char));
// ... more code here
free(buf); // don't forget this or you'll get a memory leak
This is called dynamic memory allocation (as opposed to static allocation) and it allows you nice things like changing the amount of allocated memory at runtime using realloc
or using a variable in the malloc
call.
Also note that memory allocation can fail if the amount of memory is too large, in this case the returned pointer will be NULL
.
Technically, sizeof(char)
above isn't needed because 1 char
will always be 1 byte in size, but most other data types are bigger and the multiplication is important - malloc(100)
allocates 100 bytes, malloc(100 * sizeof(int))
allocates the amount of memory needed for 100 int
s which usually is 400 bytes on 32-bit systems, but can vary.
int amount = calculate_my_memory_needs_function();
int* buf = malloc(amount * sizeof(int));
if (buf == NULL) {
// oops!
}
// ...
if (more_memory_needed_suddenly) {
amount *= 2; // we just double it
buf = realloc(buf, amount * sizeof(int));
if (!buf) { // Another way to check for NULL
// oops again!
}
}
// ...
free(buf);
Another useful function is calloc
that takes two parameters (first: number of elements to allocate, second: size of an element in bytes) and initializes the memory to 0.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…