Search code examples
cmigration64-bit32bit-64bit

Crash occurred when assigning size_t with int variable


I have below code.

#include<stdio.h>

void func(size_t *ptr)
{
    printf("Before *ptr = %d &ptr = %p\n",*ptr, &ptr);
    unsigned int len = 100;
    *ptr = len;
    printf("After *ptr = %d &ptr = %p\n",*ptr, &ptr);
}
void main()
{
    int var = 10; 
    
    printf("Before var = %d &var = %p\n",var, &var);
    func((size_t *)&var);
    printf("After var = %d &var = %p\n",var, &var);
    return;
}

This code is working fine in 32 bit environment. I'm migrating the application to 64bit and in this case, code generates a core dump. It works fine in few online compiler such as code codepad.org but crashes in programiz.

I understand that in 64 bit environment size_t size would be 8byte but in case of 32 bit it is 4 byte. So I managed to solve this by changing the below line.

size_t var = 10; 

So my question is, is it wrong to assign a pointer of lower data size(for instance int) to higher data size?(For example long/size_t)

What has caused the issue in this scenario?

What are the other things I should be taking care related to pointer when migrating to 64bit environment?


Solution

  • int main(void)
    {
        printf("sizeof(size_t) = %zu , sizeof(int) = %zu\n", sizeof(size_t), sizeof(int));
    }
    

    On my system sizeof(size_t) is larger than sizeof(int).

    In your function, you write and read data from the memory which is outside the int variable you passed by the pointer. You access memory which was not allocated to your variable and invoke Undefined Behaviour (UB).