字符串里面的功能:自动变量或堆中分配的? [英] String literals inside functions: automatic variables or allocated in heap?

查看:120
本文介绍了字符串里面的功能:自动变量或堆中分配的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们是用在函数内部的自动变量的字符串?或者,他们是我们必须手工释放堆分配?

Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?

我已经喜欢code的情况如下图所示,其中我指定一个字串类(标记为在code ONE)的私人领域,很久以后我的程序检索它和使用它(标示为二)。我是否分配在堆栈中的一个字段的一个变量?在code可被引用到一个悬摆指针在这种情况下工作,因为该方案是足够小?

I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?

我编译并运行它,它工作得很好,但我有我的地方我指定字符串像这样的类的字段实际程序一个奇怪的崩溃,我怀疑我在上面提到的情况。

I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above.

#include <iostream>

using namespace std;

class MemoryLeak
{
private:
    char *s;
public:
    MemoryLeak() {}

    void store()
    {
        s = "Storing a string"; // ONE
    }

    char *retrieve()
    {
        return s;
    }
};

int main()
{
    MemoryLeak *obj = new MemoryLeak();
    obj->store();
    cout << obj->retrieve() << endl; // TWO
    delete obj;
    return 0;
}

我应该声明变量s作为一个字符数组,而不是一个指针?我打算使用std ::字符串,但我只是好奇这个问题。

Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this.

任何指针或帮助是一如既往的多AP preciated :)谢谢。

Any pointers or help is, as always, much appreciated :) Thanks.

推荐答案

字符串字面量将被放置在初始化数据或文字(code)编译器的二进制段,而不是居住在(运行时分配的)存储器或堆栈。所以,你应该用一个指针,因为你将要引用的字符串,编译器为你已经产生。请注意,修改此(这将需要改变内存保护典型值)将改变这个文字的所有用途。

String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.

这篇关于字符串里面的功能:自动变量或堆中分配的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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