I was experimenting with the pointers. I initially, created a pointer to a character and allocated a size of 2 bytes the pointer. Then I ran loop till 1000 assigning some values. When I try to print the String it gives me a whole set values that have been assigned.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char *a = (char *)malloc(2);
for (int i=0;i<10;i++)
a[i]='a';
cout<<a<<"\t"<<strlen(a)<<"\n";
return 0;
}
The output will be as follows
aaaaaaaaaa 10
I ran the same code in both C and C++. They are giving me the same result.
As of a first thought, since I used the pointers, a[3] mean *(&a + 3): which would explain why I am able to assign a value to that location. But, even when I allocated only two bytes of memory to String, Why is my string length being varied? Why is that the compiler behaving in a different manner? What goes behind the screen?
OS: OS X 10.10.0 compiler: gcc || g++ Architecture: 64-bit Architecture
Edit1: It is not about the seg fault.
Edit2: If it is because the strlen reads until it encounters a null terminator. I haven't declared it at the end of the string.