Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program crashes after pointer arithmetic (only in some computers)

Tags:

c

pointers

crash

I have the following code (I didn't write it and it is simplified to only show the problematic part):

#include <stdlib.h>

typedef struct test_struct {
    unsigned int foo;
    char *dummy;
} test_struct;

int main()
{
    test_struct *s = (test_struct *) malloc(10 * sizeof(test_struct));
    s = (test_struct *)((unsigned long)s + 16);
    s->foo = 1; // crash!
}

The program allocates memory for 10 structs (10*24 bytes in my platform). Then, the pointer gets an addition of 16 bytes, and it tries to write a number in that position.

I have tested this snippet in 4 computers. Two of them are running on Windows 7 x64, and it works well. Another one running on lubuntu x64, and works as expected, too. The other one is a Windows 10 x64, and it crashes.

Could you help me to understand what is wrong in those lines? I'm using a third party library that does this and I don't know what is really happening.

like image 762
Zuhaitz Beloki Avatar asked Aug 12 '26 21:08

Zuhaitz Beloki


1 Answers

s = (test_struct *)((unsigned long)s + 16);

On some platforms long is not enough to store a pointer, so use uintptr_t instead:

s = (test_struct *)((uintptr_t)s + 16);

The program allocates memory for 10 structs (10*24 bytes in my case). Then, the pointer gets an addition of 16 bytes

Whatever you are trying to achieve, please note the size of the structure is also platform dependent. Not only the fields inside the structure, but padding might also be different on different platforms.

So in calculations we better use sizeof and offsetof instead of magic numbers like 16.

like image 83
Andriy Berestovskyy Avatar answered Aug 14 '26 15:08

Andriy Berestovskyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!