Interesting Code in Cpp

I was just trying to clear some doubts on the sizes of pointers returned by the cpp compiler and I came across this anomaly or we can say a type of vulnerability in cpp, I had studied about this but had never done this practically. I was trying to access the elements of a char* and by mistake gave the end limit more than the number of letters in the string, but surprisingly I got the output which I shouldn't have got. I got the values stored in the ROM as the char* data is stored in the ROM segment of the memory.
This is the code which was implemented in online compiler of Programiz and the output which I got as a result :-
#include<iostream>
#include<limits.h>
using namespace std;
int sum(int a, int b){
    return a+b;
}
string sum(float a,int b){
    return "Foo";
}
int main() {
    const char* s="Him\0esh";
    string s1="Himesh";
    char d='d';
    cout<<"Hola Todo El Mundo!\n";
    /** Getting the size of below string as 7 **/ 
    cout<<sizeof("Himesh")<<endl;
    
    /* But the size of the below variable(string) is 
     * being given as 8 
     */
     // We can't change the char* bcz it is stored in the ROM
    //  s[6]='a';
    cout<<sizeof(s)<<endl;
    //And size of s1(string var) is being given as 32    
    cout<<sizeof(s1)<<endl;
    cout<<sizeof(float*)<<endl;
    cout<<s<<endl;
    // Accessing memory and changing it 
    for(int i=0;i<300;i++){
        s1[i]=char(((i)%26)+65);
    }
    for(int i=0;i<30;i++){
        cout<<s1[i]<<" ";
    }
    cout<<endl;
    // Accessing the ROM, not belonging to me
    for(int i=0;i<3009;i++){
        cout<<s[i]<<" ";
    }cout<<endl;
    
    /** Why the compiler is considering the below number as a double? **/
    // cout<<sizeof(11.1);
    return 12343;
}


Comments

Popular Posts