c - Strings, char array sizes, and calloc --- what causes this segmentation fault? -


To keep this question low, briefly summarize (no check for tap, etc.) are the following.

program1.c

  main () {char * aString = calloc (10, size (four)); Printf ("Enter String" :); Scanf ("% s", aString); Printf ("You typed in% s \ n", aString); }   

program2.c

  main () {char aString [10]; Printf ("Enter String" :); Scanf ("% s", aString); Printf ("You typed in% s \ n", aString); }   

program1.c I think enter the letters forever. I have entered 2000+ characters and despite this fact the program will execute without error, it is "undefined behavior".

program2.c will enter more than 10 characters, but if coming closer to 30 or 40 characters, then this will give me a split mistake.


Now my limited understanding of class and other tutorials tells me that these two programs are doing the same thing under the hood --- the array of characters in length of 10 pieces towards a piece of memory Have to be But it seems that implementation of program2.c provides some protection. Or breakdown fault error is completely random when you exceed memory space, and I just get it with program2.c just because the mood is in my computer right now?

What is the difference between program1.c and program2.c, and what is the "safe" method of entering the string? I know that can be better than other methods, but I am curious about the comparison between these two.

Although neither program is safe, you are probably looking at behavior, it is that program B stack On the array allocates, and as soon as you get out of range, you are overwriting other useful things such as stack frame scanf call.

While Program A hovers the memory, and since you are not doing anything else in this toy program, the memory you are writing to is unused.

In any of the actual programs, both are equally unsafe.

Note: This behavior outside the range is undefined from the C standard, and the compiler may do theoretically anything but in the most common real world compiler, most likely the fact What happens in.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -