我什么时候应该在 C 中使用 malloc,什么时候不应该? [英] When should I use malloc in C and when don't I?

查看:51
本文介绍了我什么时候应该在 C 中使用 malloc,什么时候不应该?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 malloc() 的工作原理.我的问题是,我会看到这样的事情:

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?

推荐答案

char *some_memory = "Hello World";

正在创建一个指向字符串常量的指针.这意味着字符串Hello World"将位于内存的只读部分中的某个位置,而您只有一个指向它的指针.您可以将该字符串用作只读.您不能对其进行更改.示例:

is creating a pointer to a string constant. That means the string "Hello World" will be somewhere in the read-only part of the memory and you just have a pointer to it. You can use the string as read-only. You cannot make changes to it. Example:

some_memory[0] = 'h';

自找麻烦.

另一方面

some_memory = (char *)malloc(size_to_allocate);

正在分配一个字符数组(一个变量)并且 some_memory 指向分配的内存.现在这个数组既可以读也可以写.你现在可以这样做:

is allocating a char array ( a variable) and some_memory points to that allocated memory. Now this array is both read and write. You can now do:

some_memory[0] = 'h';

并且数组内容变为hello World"

and the array contents change to "hello World"

这篇关于我什么时候应该在 C 中使用 malloc,什么时候不应该?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆