C ++ SegFault when dereferencing a pointer to cout

I am new to C ++ and just trying to understand it. This is usually not so bad, but I came across this weird / pathological behavior:

int main () {
  int* b;
  *b = 27;
  int c = *b;
  cout << "c points to " << c << endl; //OK                                                                                                                                      
  printf( "b points to %d\n", *b); //OK                                                                                                                                          
  // cout << "b points to " << (*b) << endl; - Not OK: segfaults!                                                                                                               
  return 0;
}

This program, as indicated, creates what you expect:

c points to 27
b points to 27

On the other hand, if you uncomment the line "second-last", you get a program that crashes (seg-fault) at run time. What for? This is a valid pointer.

+5
source share
5 answers

int* b , . (0 NULL ++, nullptr ++ 0x), segfault . , , , . :

int c = 27;
int* b = &c;

cout << "c points to " << c << endl;
printf ("b points to %d\n", *b);
cout << "b points to " << (*b) << endl;

, int* b , ( ).

, , , , . , new :

int* b = new int();
*b = 27;
int c = *b;

//output

delete b;
+7

3

, -, , ++ undefined ?, , undefined . ++ , 24.2 , 24.2.1 5 10, ( ):

[...] [: x ( int * x;), x , a . -end example] [...] .

2

C , , , . , , , ++.

b , , b, undefined .

b , :

int a ;
int* b = &a;

new.

, undefined, ++ 5.3.1 , 1, ( ):

* : , , , - lvalue, , . [...]

3.10 Lvalues ​​ rvalues, 1 ( ):

l ( , , lvalues ​​ ) . [...]

b .

- f b, , undefined .

, , , , gcc -Wall :

warning: 'f' is used uninitialized in this function [-Wuninitialized]

f :

char a ;
char *f = &a ;

, C FAQ - .

, C99 J.2 undefined 1 :

undefined :

:

, (6.2.4, 6.7.8, 6.8).

f b , .

, undefined, 6.5.2.5 , 17, , , :

[...] p , undefined.

C11 16.

+9

, . , , . , , , .

, , .


:

int* b; // b is uninitialized.
*b = 27;

b ? - , - . .

, .

int b1 = 27;
int *b = &b1;

b , b1.

+3

, f - , .

+1

:

char* f;is a variable. *f- use of this variable. Like any variable, it will be initialized before use f.

+1
source

All Articles