Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a seg fault when I use ++ but not when I use '1 +'?

Please explain why I get the segfault using the ++ operator. What is the difference between explicitly adding 1 and using the ++ operator ?

using namespace std;
#include <iostream>

int main() {

  char* p = (char*) "hello";

  cout << ++(*p) << endl; //segfault
  cout << 1 + (*p) << endl; // prints 105 because 1 + 'h' = 105  

} 
like image 680
Kacy Raye Avatar asked Dec 29 '25 03:12

Kacy Raye


1 Answers

Because you're trying to increment a constant.

char* p = (char*) "hello";  // p is a pointer to a constant string.
cout << ++(*p) << endl;     // try to increment (*p), the constant 'h'.
cout << 1 + (*p) << endl;   // prints 105 because 1 + 'h' = 105

In other words, the ++ operator attempts to increment the character p is pointing to, and then replace the original value with the new one. That's illegal, because p points to constant characters. On the other hand, simply adding 1 does not update the original character.

like image 182
Adam Liss Avatar answered Dec 30 '25 17:12

Adam Liss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!