简体   繁体   中英

Difference between storing values in character pointer with malloc and without

I have a character pointer like this

  char *ptr;

I can allocate values to it like this

  *ptr='a';
  *(ptr+1)='b';

Now when I can do this, why should I use an malloc?

Am I just lucky that this pointer is not referencing an address that is being used by a process? Or are there chances that my data will be corrupted by someother process if I don't use 'malloc'?

Am I just lucky that this pointer is not referencing an address that is being used by a process?

No, you're not lucky. If you were lucky, the program would crash so you know you have a problem. As written, your code is Undefined Behavior . You are writing data through a pointer to unallocated memory.

§ 6.5.6/8
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

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