Home > Blockchain >  Values are not getting assigned to continuous addresses
Values are not getting assigned to continuous addresses

Time:09-17

Why on compiling the below piece of code is giving runtime error?

#include<stdio.h>

int main() 
{
    int i;
    int *p;
    int a = 10;
    p= &a;
    
    printf("address of a = %x\n",p);
    *(p   0) = 5;
    *(p   1) = 6;
    *(p   2) = 7;
    *(p   3) = 8;
    
    for(i=0; i < 4; i  )
    {
        printf("address = %x value = %x\n",(p i),*(p i));
    }
    return 0;
}

In this code i am assigning values to the address of variable named a after that starting from address of a the values (6,7,8) respectively are getting assigned to the next address of a consecutively.

CodePudding user response:

*(p   1) = 6;

p is an int* - meaning that when you increment it by one, it doesn't jump one byte forwards - it jumps sizeof(int) bytes forward (probably 4 bytes). If you want to assign to the bytes separately, cast the pointer to a char*:

*((char*)p   1) = 6;

When you write code like *(p 1) = 6; - your program is very likely to crash. Per the standard this is undefined behavior, in practice what usually really happens behind the scenes is that since p == &a and a is on the stack, p 1 points to 4 bytes in the stack above a - which likely contains some random value like a stack canary or a return address - and you are corrupting this value.

CodePudding user response:

These expressions:

*(p   1) = 6;
*(p   2) = 7;
*(p   3) = 8;

Create pointers that are past the memory bounds of a which are then subsequently dereferenced. Reading memory past the bounds of an object (or even attempting to create such a pointer if it is not just past the object) triggers undefined behavior.

In this particular case it caused your program to crash, but there is no guarantee that will happen.

CodePudding user response:

You should allocate that memory before accessing it. Try using malloc().

CodePudding user response:

Your code should look like this:

#include<stdio.h>

int main() 
{
    int i;
    int a = 10;
    char *p= (char *)&a;
    
    printf("address of a = %p\n",p);

    for (i = 0; i < sizeof(a);   i) {
        *(p   i) = i   5;
    }
    
    for(i = 0; i < sizeof(a);   i) {
        printf("address = %p value = %d\n", p   i, *(p   i));
    }

    return 0;
}

One solution is to define p as a pointer to char. Another approach is, as suggested in other answers, just cast p into a pointer to char before any arithmetic. When using pointer arithmetic, the number of bytes you "jump" is as the size of the pointed type. So, p 1 will jump 4 bytes, in case int is 4 bytes. This is why you should use a pointer to char if you want to move one byte at a time.

In addition, your loops should run N times, where N in the number of bytes. So, my suggestion is to use sizeof.

Last thing, please note that in order to print an int you should use %d, and use %p to print pointers (i.e addresses).

  • Related