Tiny program

The following program compiles with g ++, but then fails to start:

class someClass
{
public:
    int const mem;
    someClass(int arg):mem(arg){}
};

int main()
{
    int arg = 0;
    someClass ob(arg);

    float* sample;
    *sample = (float)1;

    return 0;
}

The following program does not crash:

int main()
{

    float* sample;
    *sample = (float)1;

    return 0;
}
0
source share
4 answers
float* sample;
*sample = (float)1;

sampleit is never initialized to point to an object, so when you cast it, your program crashes. You need to initialize it before using it, for example:

float f;
float* sample = &f;
*sample = (float)1;

- , . , , undefined. , , . , , .

+8

, .

, crt (c runtime) 3: (int), char ** char **, main.

, main, , 2 , . , , . , :

+--------+
| # args |  
+--------+    
|  args  |  
+--------+  <------ stack pointer
|  envs  |  
+--------+  

int , , :

+--------+
| # args |  
+--------+    
|  args  |  
+--------+  <------ stack pointer
|  arg   |  <------ your integer, initialized in code
+--------+  
|   ob   |  <------ your struct, initialized in code
+--------+  
| sample |  <------ your pointer, uninitalized = garbage
+--------+  

sample - .

:

+--------+
| # args |  
+--------+    
|  args  |  
+--------+  <------ stack pointer
| sample |  <------ pointer, uninitalized (!)
+--------+  

- , , , envp, : char **. , " char", ( ). , .

, , , , ? gdb, (char**)sample , .

MSV++ 10 32- ( ):

http://img651.imageshack.us/img651/5918/69916340.png

+4

.

: ,

BTW: (gcc 4.4, amd64) .

, , .

0

All Articles