Why does not it give segmentation fault when I write to a char * without allocating memory?

3

My question is whether the compiler automatically allocates memory for the variable s1

char *s1;
char s2[20];

//s1=(char*)malloc (sizeof(char)*20);
s1="palavra1";

strcpy (s2,"palavra2");


printf("s1:%s\ns2:%s\n",s1,s2);

Apparently if I do the allocation that is in comment, it has the same output , that is, the palavra1 is printed on it.

The same situation occurs when I do the following:

char *s1 = "teste";
char s2[20];

//s1=(char*)malloc (sizeof(char)*20);
//s1="palavra1";

strcpy (s2,"palavra2");


printf("s1:%s\ns2:%s\n",s1,s2);

Will print the word "test" and "word1"

What can I complete from here?

    
asked by anonymous 26.04.2016 / 19:03

1 answer

4

Because C does not have to allocate memory. The language can access your entire address space in an insecure way. C is powerful, performance and flexible, at the cost of robustness. If the programmer says he wants to access an area of memory, the language leaves. Segment failure will only occur if the memory segment is protected for write access, which is not the case.

It is working what was written, but it will stop working what was in memory previously. In this example it will work because it is very simple. In a more complex application it would probably compromise memory.

Could have picked up an address outside of the application's accessible area, there would be an error.

Without allocating memory, what is the value of s1 ? It's what was in memory earlier. In C the memory is not cleared in the declaration of its allocation. C only reserves one space for use, in this case in the application stack. This "dirt" is giving "luck" to be something that performs. You might try it later and something else will happen.

In all languages it is not enough to test to see if it is right. Yes, the test would be enough if it were really possible to test every possible situation. But it's virtually impossible for anyone to do this. That's why you always have to understand how everything works and know what you're doing. Testing is never the solution, only test that works in a given situation, does not prove that it does not work. I would like every programmer to understand at least this.

In C this is even more valid.

The conclusion is that this code is wrong, even though it "passes the test".

    
26.04.2016 / 19:16