简体   繁体   中英

Who initialize a char pointer inside a struct on the stack

Its generally known that things on the stack are not initialized by default. I tried to prove that with a struct on the stack, but unexpectedly my pointer is initialized with null, but why? What is initializing this pointer?

#include <stdio.h>
#include <string.h>

struct strustri {
    int var1;
    char *var2;
};

int main()
{
    struct strustri test1 = {
            .var1 = 12,
            .var2 = "Teststring",
    };
    struct strustri test2;

    printf("test1.var1 is %d\n", test1.var1);
    printf("test2.var1 is %d\n", test2.var1);

    printf("test1.var2 points to %p\n", test1.var2);
    printf("test2.var2 points to %p\n", test2.var2);
    return 1;
}

And this is the output on my machine (Ubuntu 12.10):

test1.var1 is 12
test2.var1 is -1271814320
test1.var2 points to 0x400634
test2.var2 points to (nil)

I ran my example multiple times. I get another value for var1 everytime, but var2 is always points to zero (null pointer)...

Nothing is initializing it.

It's just an artefact of whatever rubbish happens to be on your stack. Switch the order of the variable declarations, or add some more local variables, and you'll get a different result.

如果将测试结构放在单独的函数中,那么还有另一个函数可以创建一个char数组(例如200字节长),并用一些字母填充该字符,然后交替调用这两个函数,您会注意到test2中的值将会有所不同(最有可能,但不能100%保证-由于我们正在处理“不确定的行为”,因此可能会发生其他情况)。

when int var1 is executed to create space for test2, it has create space for itself but if you don't assign a value to it then it will show the value which was already there..

but in case of var2, it is a pointer. if pointers are not initialized then it does not point to anything, making it nil or NULL or '\\0'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM