Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory for a part of structure

I have the following example

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

typedef struct test{
    int a;
    long b;
    int c;
} test;

int main()
{
    test *t = (test*) malloc(offsetof(test, c));
    t -> b = 100;
}

It works fine, but Im not sure about it. I think I have UB here. We have a pointer to an object of a structure type. But the object of the structure type is not really valid.

I went through the standard and could not find any definition of this behavior. The only section I could find close to this one is 6.5.3.2:

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined

But this is not really relevant since the pointer returned by malloc is completely valid.

Is there a reference in the standard explaining such a behavior? I'm using C11 N1570.

like image 874
St.Antario Avatar asked Dec 23 '18 14:12

St.Antario


1 Answers

From C2011, paragraph 6.2.6.1/4:

Values stored in non-bit-field objects of any other object type consist of n x CHAR_BIT bits, where n is the size of an object of that type, in bytes.

Therefore, since the allocated object in your code is smaller than the size of a struct test, it cannot contain a value of an object of that type.

Now consider your expression t -> b = 100. C2011, paragraph 6.5.2.3/4 defines the behavior of the -> operator:

A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points [...].

(Emphasis added.) We've established that your t does not (indeed, cannot) point to a struct test, however, so the best we can say about 6.5.2.3/4 is that it does not apply to your case. There being no other definition of the behavior of the -> operator, we are left with paragraph 4/2 (emphasis added):

If a ''shall'' or ''shall not'' requirement that appears outside of a constraint or runtime- constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ''undefined behavior'' or by the omission of any explicit definition of behavior.

So there you are. The behavior of your code is undefined.

like image 118
John Bollinger Avatar answered Oct 20 '22 09:10

John Bollinger