Why more string is added than allocated memory [duplicate] - c

This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 6 years ago.
Following is code snippet :
char *b = NULL;
b = new char[5];
if(b != NULL) {
printf("b=%p\n",b);
sprintf(b, "helloPLS...123456789123456789");
printf("b = %s\n", b);
}
output : b = helloPLS...123456789123456789
If only 5 bytes were allocated then why all "helloPLS...123456789123456789" string is added into 5 byte memory?
My program works perfectly fine.

You are writing past the end of memory you allocated. The C standard clearly says the behavior in this case is undefined.
And undefined behavior doesn't mean "always crash". It means it may appear to work. It means the implementation of your C run time environment is within its right to do anything it desires, and that will still be standard compliant.
Undefined behavior is something you should carefully watch out for, precisely because your program may "work perfectly fine" until it just won't.

Related

How does arrays bypass its declared length [duplicate]

This question already has answers here:
How dangerous is it to access an array out of bounds?
(12 answers)
Why doesn't my program crash when I write past the end of an array?
(9 answers)
Array index out of bound behavior
(10 answers)
No out of bounds error
(7 answers)
Closed 3 years ago.
I was making practises on the logic of arrays in c and my thought on the array length declaration was unformattable if you declare an array length to be 10 integers, that array could not keep 20 integers in memory but when I tested it I saw that I was completely wrong
int main(){
int i;
int arr[10];
for (i = 0;i<20;i++){
arr[i] = i;
}
for (i = 0;i<20;i++){
printf("%d \n",arr[i]);
}
}
I was expecting to see 10 printed numbers but it prints out 20 could someone explain how is it possible?
C and C++ don't have explicit bounds checking on array sizes. When you read/write past the end of an array, you invoke undefined behavior.
With undefined behavior, your program may crash, it may output strange results, or (as in your case) it could appear to work properly. Also, making a seemingly unrelated change such as adding an unused local variable or adding a printf for debugging can change how UB manifests itself.
Just because a program may crash doesn't mean it will.

Why does "int x = 5; printf("%d %d %d", x==5, x=10, x==5);" in C print "0 10 0"? [duplicate]

This question already has answers here:
issue with assignment operator inside printf()
(3 answers)
How to understand the behaviour of printf statement in C?
(5 answers)
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 3 years ago.
I've been studying C for about a year now, and I came across this above when I was just playing around. I first thought maybe it's a case of assignment precedence (i.e. x=10 happens first), but then I tried
printf("%d %d %d", x==5, x=10, x<6);
and it outputs
0 10 1. Could someone please explain to me why/what is going, as this seems extremely baffling to me and I'm starting to think it's undefined behavior perhaps?
This is indeed undefined behavior. Arguments to functions are evaluated in an unspecified order, so doing anything that relies on that order becomes UB.
It looks like your compiler goes right-to-left (at least in this instance). That's a reasonable way to do it. But since it's UB, don't count on it always doing that.

diferent behaviour in different environments for uninitialised malloced memory [duplicate]

This question already has answers here:
Why does malloc initialize the values to 0 in gcc?
(10 answers)
Closed 5 years ago.
I was implementing a program related to the use of dynamic allocation in C.
Testing the same piece of code on Visual Studio 2017 and on other IDEs (Dev C ++, Codeblocks, etc.) I have different behaviors:
size_t newDim = 9;
char *p = malloc((newDim + 1) * sizeof(char));
p[newDim] = '\0';
printf("%d\n", strlen(p));
The output of printf() on Visual studio is: 9
other IDEs: 3 sometimes 4.
But when I fill the array with dim-1 characters, the same printf() produces a correct output on the other IDEs. I think that the different compilers have a different way of managing the allocated memory, could someone explain the problem in more detail?
Thank you
malloc is not initializing the memory allocated, so the allocated space might have zeros in arbitrary places giving different string lengths.

Why does i=2+2*i++ give the wrong result? [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
I felt that such an expression should be invalid but I was able to compile it and got the answer 5.
At the end I felt that even if it does answer should be 4 not 5.
int main(void)
{
int i=1;
// how is the next line evaluated ie in what sequence??
i=2+2*i++;
printf("%d",i);
return 0;
}
The output I got was 5. I can not understand how it should give the value.
This is undefined behaviour, since i is modified more than once between sequence points. For instance, this compiler gives 4 as the answer, because it puts the increment after the assignment. Another reasonable answer is 6, if the increment is before the assignment. But, as you've found, the compiler is permitted to make the answer whatever it wants, including 5.
See here for more about sequence points and undefined behaviour.

Why out of bound array accessible in C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array index out of bound in C
Can a local variable's memory be accessed outside its scope?
C no out of bounds error
I am trying out this code snippet,
#include <stdio.h>
main(){
int a[2],i;
a[5] = 12;
for(i=0;i<10;i++){
printf("%d\n", a[i]);
}
return 0;
}
It gives me output :
1053988144
32767
0
3
0
12
-1267323827
32716
0
0
Why a[5] is accessible ? Shouldn't it through RunTime Error?
C doesn't have bounds-checking on array access, so no it shouldn't. There is nothing in the language stopping you from attempting to read every (virtual) address you can imagine, although often the operating system and/or computer itself will protest, which might generate some kind of exception. Note that just because you "can" (it compiles and run, seemingly without any ill effects), that doesn't mean the program is valid or that it "works". The results of invalid memory accesses are undefined behavior.
int a[2]; means "allocate memory that is 2 * sizeof(int)"
a[5] is syntactic sugar for *(a + 5), which point to an area of memory a + (5 * sizeof(int)). So 3 * sizeof(int) past the end of your array. Where is that? Who knows?
Some languages do bound checking, and I have heard of some C compilers that can do it as well, but most do not. Why not do bound checking? Performance. And performance is a major reason for using C in the first place. But that's OK, because C programmers are good programmers and never go beyond the bounds of an array. (hopefully)
No control is performed on index bounds. This is simply the way C works.

Resources