I'm reading a C code that do
char * buf = malloc(sizeof (char *) * 16)
instead of
char buf[sizeof (char *) * 16]
what's the difference? well, I think the first expression unnecessary, if realloc()
is not called, or am I wrong thinking?
I'm reading a C code that do
char * buf = malloc(sizeof (char *) * 16)
instead of
char buf[sizeof (char *) * 16]
what's the difference? well, I think the first expression unnecessary, if realloc()
is not called, or am I wrong thinking?
char buf[sizeof(char*)*16]
is an array allocated automatically, which is generally the stack. It is valid as long as buf is in scope, and there is sufficient stack space.
malloc
allocates memory from some heap. It is valid until this memory is free()
ed. Generally, there is much more heap available.
Yann's note is correct.
This appears to be an array of pointers. Since it is allocating memory for 16 times the size of a char pointer. Pointer size can vary on different systems. Pointers on some are 32-bit (4 bytes) where others are 64-bit (8 bytes).
char buf[sizeof(char *) * 16] is not an array of pointers, it's an array of chars that has elements equal to the size of a char pointer times 16.
The first one, is a dynamic array. The expression char * buf = malloc(sizeof (char *) * 16)
stores the elements in memory ( the malloc
is basically used for memory allocation ). The advantages of using it are, you can reallocate it, i.e resize it during runtime. However, you may have to allocate new memory every time you add a new element. Here's an example:
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main() {
int* array;
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
array = malloc(n*sizeof(int));
for (i=0; i<n; i++) {
printf("Enter number %d: ", i);
scanf("%d", &array[i]);
}
printf("\nThe Dynamic Array is: \n");
for (i=0; i<n; i++) {
printf("The value of %d is %d\n", i, array[i]);
}
printf("Size= %d\n", i);
getch();
return 0;
}
The output:
The second expression char buf[sizeof (char *) * 16]
just declares a boring automatic array. It's size is static. No dynamic resizing, reallocation etc.
note: apologies for the type cast before malloc
. typecasting the return value of malloc will result in the compiler not giving an error if you do something wrong. This may be followed by undefined runtime errors and debugging hell. Always avoid typecasting the result of malloc
. Thanks @Lundin.
The main difference is that if this is code is in a function, you can still use the pointer declared in the former after you return.