I understand how malloc() works. My question is, I'll see things like this:
#define A_MEGABYTE (1024 * 1024)
char *some_memory;
size_t size_to_allocate = A_MEGABYTE;
some_memory = (char *)malloc(size_to_allocate);
sprintf(some_memory, "Hello World");
printf("%s
", some_memory);
free(some_memory);
I omitted error checking for the sake of brevity. My question is, can't you just do the above by initializing a pointer to some static storage in memory? perhaps:
char *some_memory = "Hello World";
At what point do you actually need to allocate the memory yourself instead of declaring/initializing the values you need to retain?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…