什么时候应该使用malloc C和没有什么时候? [英] When should I use malloc in C and when don't I?

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

问题描述

我理解的malloc()是如何工作的。我的问题是,我会看到这样的事情:

 的#define A_MEGABYTE(1024 * 1024)字符* some_memory;
为size_t size_to_allocate = A_MEGABYTE;
some_memory =(字符*)malloc的(size_to_allocate);
sprintf的(some_memory,的Hello World);
的printf(%S \\ n,some_memory);
免费(some_memory);

我省略错误检查简便起见。我的问题是,你不能只是做上述通过初始化一个指向内存中的一些静态存储?或许是:

 的char * some_memory =Hello World的;

在什么时候你真的需要分配自己的内存而不是声明/初始化你需要保留价值?


解决方案

 的char * some_memory =Hello World的;

是创建一个指向字符串常量。这意味着字符串Hello World将在内存的只读部分地方,你只是有一个指针。您可以使用该字符串为只读。您不能进行更改。例如:

  some_memory [0] ='H';

是自寻烦恼。

在另一方面

  some_memory =(字符*)malloc的(size_to_allocate);

被分配一个字符数组(变量)和some_memory指向分配的存储器。现在,这个数组是读写。现在你可以这样做:

  some_memory [0] ='H';

和数组内容更改为Hello World

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\n", 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";

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';

Is asking for trouble.

On the other hand

some_memory = (char *)malloc(size_to_allocate);

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';

and the array contents change to "hello World"

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

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