加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 堆与数据段与堆栈分配

发布时间:2020-12-16 05:56:11 所属栏目:百科 来源:网络整理
导读:我正在看下面的程序,不知道如何分配内存,为什么: void function() { char text1[] = "SomeText"; char* text2 = "Some Text"; char *text = (char*) malloc(strlen("Some Text") + 1 );} 在上面的代码中,最后一个代码显然是在堆中.但是,据了解,text2在程序
我正在看下面的程序,不知道如何分配内存,为什么:
void function() {
    char text1[] = "SomeText";
    char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}

在上面的代码中,最后一个代码显然是在堆中.但是,据了解,text2在程序的数据段中,而text1可能位于堆栈中.还是我的假设错了?这里有什么正确的假设?这个编译器是否依赖?

谢谢

解决方法

// Array allocated on the stack and initialized with "SomeText" string.
// It has automatic storage duration. You shouldn't care about freeing memory.
char text1[] = "SomeText"; 

// Pointer to the constant string "Some Text".
// It has static storage duration. You shouldn't care about freeing memory.
// Note that it should be "a pointer to const".
// In this case you'll be protected from accidential changing of 
// the constant data (changing constant object leads to UB).
const char* text2 = "Some Text";

// malloc will allocate memory on the heap. 
// It has dynamic storage duration. 
// You should call "free" in the end to avoid memory leak.
char *text = (char*) malloc(strlen("Some Text") + 1 );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读