return pointer to data declared in function

前端 未结 11 1593
南旧
南旧 2020-12-17 21:11

I know this won\'T work because the variable x gets destroyed when the function returns:

int* myFunction()
{
    int x = 4; return &x;
}
<
11条回答
  •  庸人自扰
    2020-12-17 21:26

    Your second code snippet is correct.

    To help avoid memory leaks, I let the coding conventions help me.

    xxxCreate() will allocate memory for xxx and initialize it. xxxDelete() will destroy/corrupt xxx and free it.

    xxxInit() will initialize xxx (never allocate) xxxDestroy() will destroy/corrupt xxx (never free)

    Additionally, I try to add the code to delete/destroy/free as soon as I add the code to create/init/malloc. It's not perfect, but I find that it helps me differentiate between items that need to be freed and those that don't, as well as reducing the likelihood that I will forget to free something at a later time.

提交回复
热议问题