开发者

Passing pointer: different value in stack?

开发者 https://www.devze.com 2023-02-05 08:29 出处:网络
I do: typedef struct { Scene *scene; MeshStore *store; float angle; } DebugModel ... free_entire_store(debug_model.store);

I do:

typedef struct {
    Scene *scene;
    MeshStore *store;
    float angle;
} DebugModel

...
free_entire_store(debug_model.store);

/* Frees the store and any meshes related to it */
void free_entire_store(MeshStore *store) {
   /* implementation not important for the problem at hand */
}

Now, if I gdb this putting a breakpoint at the beginning of free_entire_store I get the following strange data..

(gdb) p debug_model  
$5 = {scene = 0x1044a680, store = 0x1044a630, angle = 87.8401108}  
(gdb) p store  
$6 = (MeshStore *) 0x10438b40
开发者_如何学C

debug_model is a global, the above debugging output is from the same point int he program.

So, even though I simply pass the pointer as a parameter, it somehow gets changed. The stack is corrupted, albeit in a very predictable manner (the same data appears every run). What could have caused this? I don't think I freed anythign twice or something before calling this function. How can the value passed as parameter not correspond with the value in the stack?


Are you sure you placed the breakpoint correctly? store might not yet be assigned, especially if you compiled with optimisations. Try breaking after the first line of the method to be sure it is assigned already.


I think it's because you are making a copy of the pointer in the function so it can be modified locally. Both should point to the same thing.

If you want to use the exact same pointer inside the function and outside, you should pass a pointer to a pointer.

typedef struct {
    Scene *scene;
    MeshStore *store;
    float angle;
} DebugModel

...
free_entire_store(&(debug_model.store));

/* Frees the store and any meshes related to it */
void free_entire_store(MeshStore **store) {
    MeshStore *originalStore = *store;
    /* implementation not important for the problem at hand */
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号