0
int main( ){    
    char a[2];
    char *p;
    p=&a[0];
    *(p+5)='g';
}

In the above program I defined a pointer pointing to char array but the array is 3 bytes only. Let me tell you more clearly,for instance let us assume the char array address is 1000 so it takes upto 1003 bytes, but using a pointer I am storing an ASCII value of 'g' at 1005 location. Is that okay with the compiler ? Is that memory an static alloacted one ? or Can be used again ? Will that value be permanently stored in it or no?

2
  • 1
    You're writing into memory that hasn't been allocated so the behavior is undefined. Commented Jul 1, 2011 at 5:36
  • 2
    Hang on - the array is 2 bytes only, not 3. Commented Jul 1, 2011 at 5:37

4 Answers 4

4

You are changing a random memory location in your program. This is undefined behavior and it could have random effects on your program such as a segmentation fault.

Sign up to request clarification or add additional context in comments.

3 Comments

@cody: Yes, but how is the compiler supposed to know that the memory location you are pointing to is invalid?
@cody char* p = ((char*)rand()) I have a pointer to it! unfortunately that doesn't mean using it will not crash your program horribly
@tobyodavies: Now that's just scary
3

char array address is 1000 so it takes upto 1003 bytes

Typically a char is 1 byte in length. So a char array having 2 chars will take two bytes: 1000 and 1001.

Is that okay with the compiler ?

It is fine with the compiler. C allows you to do whatever thing you want to do, including crashing the system.

Is that memory an static alloacted one ? or Can be used again ? Will that value be permanently stored in it or no?

That memory is not allocated to be used by your program. You promised that you'll be using only location 1000 and 1001. If you access anything beyond that, that is undefined behaviour. Anything can happen and nothing is guaranteed in such cases.

Comments

2

This is fine by the compiler, but might cause a problem at runtime, since who knows what's at the address you're writing to.

Comments

1

first of all you have declared char array to hold only 2 chars and not 3. If you attempt this the behavior will be undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.