I always wonder why C manages the memory the way it does.
Take a look at the following codes:
int main(){
int x = 10000000000;
printf("%d", x);
}
Of course, overflow occurs and it returns the following number:
1410065408
Or:
int main(){
int x = -10;
printf("%u", x);
}
Here x is signed and I am using the unsigned keyword "%u"
Returns:
4294967286
Or take a look at this one:
int main(){
char string_ = 'abc';
printf("%d", string_);
}
This returns:
99
That being said, I mainly have two questions:
- Why the program returns these specific numbers for specific inputs? I don't think it is a simple malfunctioning because it produces the same result for the same input. So there is a deterministic way for it to calculate these numbers. What is going under the hood when I pass these obviously invalid numbers?
- Most of these problems occur because C is not a memory-safe language. Wikipedia says:
In general, memory safety can be safely assured using tracing garbage collection and the insertion of runtime checks on every memory access
Then besides historical reasons, why are some languages not memory-safe? Is there any advantage of not being memory-safe rather than being memory-safe?