何时将 malloc 用于 char 指针 [英] When to use malloc for char pointers

查看:17
本文介绍了何时将 malloc 用于 char 指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特别关注何时在 char 指针上使用 malloc

I'm specifically focused on when to use malloc on char pointers

char *ptr;
ptr = "something";
...code...
...code...
ptr = "something else";

malloc 会为了这样微不足道的事情而存在吗?如果是,为什么?如果没有,那么什么时候需要 char 指针?

Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?

推荐答案

正如其他人所指出的,您不需要使用 malloc 来做:

As was indicated by others, you don't need to use malloc just to do:

const char *foo = "bar";

原因正是 *foo 一个指针 —当您初始化 foo 时,您并没有创建字符串的副本,只是一个指向 "bar" 位于可执行文件的数据部分中的位置的指针.您可以随意复制该指针,但请记住,它们总是指向该字符串的同一个实例.

The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.

那么什么时候应该使用 malloc?通常你使用 strdup() 来复制一个字符串,它在后台处理 malloc.例如

So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.

const char *foo = "bar";
char *bar = strdup(foo); /* now contains a new copy of "bar" */
printf("%s
", bar);     /* prints "bar" */
free(bar);               /* frees memory created by strdup */

现在,我们终于解决了一个情况,如果您使用 sprintf() 或更安全的 snprintf() 来创建/格式化一个新的字符串.

Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.

char *foo = malloc(sizeof(char) * 1024);        /* buffer for 1024 chars */
snprintf(foo, 1024, "%s - %s
", "foo", "bar"); /* puts "foo - bar
" in foo */
printf(foo);                                    /* prints "foo - bar" */
free(foo);                                      /* frees mem from malloc */

这篇关于何时将 malloc 用于 char 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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