Pointers and access to memory in c. Be careful

  • A+
Category:Languages

Still learning more C and am a little confused. In my references I find cautions about assigning a pointer that has not been initialized. They go on to give examples. Great answers yesterday by the way from folks helping me with pointers, here:

Precedence, Parentheses, Pointers with iterative array functions

On follow up I briefly asked about the last iteration of the loop and potentially pointing the pointer to a non-existent place (ie because of my references cautioning against it). So I went back and looked more and find this:

If you have a pointer

int *pt; 

then use it without initializing it (ie I take this to mean without a statement like *pt= &myVariable):

*pt = 606; 

you could end up with a real bad day depending on where in memory this pointer has been assigned to. The part I'm having trouble with is when working with a string of characters something like this would be ok:

char *str = "Sometimes I feel like I'm going crazy."; 

Where the reference says, "Don't worry about where in the memory the string is allocated; it's handled automatically by the compiler". So no need to say initialize *str = &str[0]; or *str = str;. Meaning, the compiler is automatically char str[n]; in the background?

Why is it that this is handled differently? Or, am I completely misunderstanding?

 


In this case:

char *str = "Sometimes I feel like I'm going crazy."; 

You're initializing str to contain the address of the given string literal. You're not actually dereferencing anything at this point.

This is also fine:

char *str; str = "Sometimes I feel like I'm going crazy."; 

Because you're assigning to str and not actually dereferencing it.

This is a problem:

int *pt; *pt = 606; 

Because pt is not initialized and then it is dereferenced.

You also can't do this for the same reason (plus the types don't match):

*pt= &myVariable; 

But you can do this:

pt= &myVariable; 

After which you can freely use *pt.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: