指向声明范围之外的局部变量的指针 [英] Pointer to local variable outside the scope of its declaration

查看:122
本文介绍了指向声明范围之外的局部变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个表示PDF文档pdf的结构和一个表示其页面pdf_page的结构:

Let's say I have a structure representing a PDF document pdf and a structure representing one of its pages pdf_page:

typedef struct pdf_page {
    int page_no;
    pdf_page *next_page;
    char *content;
} pdf_page;

typedef struct {
    pdf_page *first_page, *last_page;
} pdf;

从我的main()中,我呼叫create_pdf_file(pdf *doc):

void main() {
  pdf doc;
  create_pdf_file(&doc);
  // reading the linked list of pages here
}

假设create_pdf_file符合以下内容:

void
create_pdf_file(pdf *doc) {
    for (int i = 0; i < 10; i++) {
        pdf_page p;
        p.page_no = i;
        p.contents = "Hello, World!";
        doc->last_page->next_page = p;
    }
}

(这只是示例源代码,因此未显示列表处理.显然,首先需要设置pdffirst_pagelast_page成员.)

(This is merely an example source code, so no list processing is shown. Obviously, the first_page and last_page members of pdf need to be set first.)

我的问题:如果我在main()中的create_pdf_file()调用之后访问doc->first_page-以及链接列表中的其他页面,是否可以进行细分是因为将局部变量p从其上下文中移出"而导致错误?

My question: If I access doc->first_page - as well as the other pages in the linked list - after the create_pdf_file() call in my main(), is it possible that I get segmentation faults because of "taking the local variable p out of its context"?

(我不确定是否保证相应的内存位置不会用于其他用途.)

(I am not sure whether I have guaranteed that the corresponding memory location will not be used for something else.)

如果是这样,如何避免这种情况?

If so, how do I avoid this?

谢谢.

推荐答案

是的,p是存储在堆栈中的局部变量,当生命周期结束(每次循环迭代)时,指向它的任何指针都将变为无效.完成后,您需要使用malloc()和free()分配每个页面. 看起来类似于:

yes, p is a local variable stored on the stack, when the lifetime ends (every loop iteration) any pointer to it gets invalid. you need to allocate every page with malloc() and free() it after you are finished. this would look similar to:

for (int i = 0; i < 10; i++) 
{
        pdf_page* p = malloc(sizeof(pdf_page));
        p->page_no = i;
        p->contents = "Hello, World!";
        doc->last_page->next_page = p;
}

,当您调用函数时,必须传递一个指向doc的指针:

and when you call your function you have to pass a pointer to doc:

create_pdf_file(&doc);

这篇关于指向声明范围之外的局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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