Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

c - Dereferencing pointers without pointing them at a variable

I'm having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn't deference and assign (*p = value) unless you either malloc'd space for it (p = malloc(x)), or set it to the address of another variable (p = &a)

However in this code, the first assignment works consistently, while the last one causes a segfault:

typedef struct
{
    int value;
} test_struct;

int main(void)
{
    //This works
    int* colin;
    *colin = 5;

    //This never works
    test_struct* carter;
    carter->value = 5;
}

Why does the first one work when colin isn't pointing at any spare memory? And why does the 2nd never work?

I'm writing this in C, but people with C++ knowledge should be able to answer this as well.

Edit: Okay I get that the first one shouldn't work either, but why does it. That's what I'm after.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// This works
int* colin;
*colin = 5;

Welcome to undefined behavior: the fact that it does not crash does not mean that it works. Accessing uninitialized pointer is always wrong, yet sometimes it does not crash.

couldn't deference and assign unless you either malloc'd space for it or set it to the address of another variable

This is correct. In general, you need to point your pointer to some place that has been allocated to your program. There are multiple ways of doing that, but they all boil down to one of the two scenarios that you describe - the pointer is pointed either to a dynamically allocated memory (i.e. malloc), or to statically allocated memory (i.e. a variable).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...