sizeof issues with sdcc

Other misc things
Post Reply
alank2
Member
Posts: 116
Joined: Wed Mar 01, 2017 7:24 pm

sizeof issues with sdcc

Post by alank2 »

A number of sizeof() calls in my C code are all returning 2 instead which is true if you want to know the size of the pointer, but false if it is the sizeof a structure. sizeof(struct MyType) should reveal the size of the structure, right?
User avatar
dom
Well known member
Posts: 2076
Joined: Sun Jul 15, 2007 10:01 pm

Post by dom »

Code: Select all

#include <stdio.h>

struct x {
        long    y;
};

typedef struct x y;

int main() {
        struct x str;
        struct x *ptr;
        y       str2;
        y       *ptr2;

        printf("sizeof(str) = %d\n", sizeof(str));
        printf("sizeof(ptr) = %d\n",sizeof(ptr));
        printf("sizeof(*ptr) = %d\n",sizeof(*ptr));

        printf("sizeof(str2) = %d\n", sizeof(str2));
        printf("sizeof(ptr2) = %d\n",sizeof(ptr2));
        printf("sizeof(*ptr2) = %d\n",sizeof(*ptr2));
}
Yields:

Code: Select all

sizeof(str) = 4
sizeof(ptr) = 2
sizeof(*ptr) = 4
sizeof(str2) = 4
sizeof(ptr2) = 2
sizeof(*ptr2) = 4
on both compilers. Can you provide the related definitions and offending line?
alank2
Member
Posts: 116
Joined: Wed Mar 01, 2017 7:24 pm

Post by alank2 »

I can't argue with those results dom; when debugging something last night it was always resulting in 2 instead of what it should have been. Let me roll back and see if i can reproduce the issue again.
alank2
Member
Posts: 116
Joined: Wed Mar 01, 2017 7:24 pm

Post by alank2 »

Code: Select all

struct x {
        long    y;
        char qq[30];
};

typedef struct x y;

#if (sizeof(x)!=4)
#error fail
#endif
The #if fails with - test.c:10:12: error: missing binary operator before token "("

I don't have code to go back to and retest with, but last night I was using memcpy and sizeof(MyVariable) and the MyVariable was a uint8_t MyVariable[8]={0x11,0x22,0x11,0x22,0x11,0x22,0x11,0x22,} and it was only copying 2 bytes instead of 8. I simply defined a MYVARIABLESIZE 8 and referenced it instead which solved the problem, but I don't know what it was doing that. I can't see to get it to do it now either, but again, a lot of changes have been made. I only know that it did do it.
User avatar
dom
Well known member
Posts: 2076
Joined: Sun Jul 15, 2007 10:01 pm

Post by dom »

clang gives better diagnostics in this case:

struct3.c:8:6: error: function-like macro 'sizeof' is not defined

sizeof() isn't allowed in the pre-processor because the size of types isn't known at that stage of the processing.

Your example seems with MyVariable works as expected, so lets see if it crops again and then we can investigate.
Post Reply