转自:
https://www.ibm.com/support/knowledgecenter/en/SSXVZZ_16.1.0/com.ibm.xlcpp161.lelinux.doc/compiler_ref/bif_gcc_objectsize__builtin_object_size.html
Purpose
When used with -O2 or higher optimization, returns a constant number of bytes from the given pointer to the end of the object pointed to if the size of object is known at compile time.
Prototype
size_t __builtin_object_size (void *ptr, int type);
Parameters
ptr
The pointer of the object.
type
An integer constant that is in the range 0 - 3 inclusive. If the pointer points to multiple objects at compile time, type determines whether this function returns the maximum or minimum of the remaining byte counts in those objects. If the object that a pointer points to is enclosed in another object, type determines whether the whole variable or the closest surrounding subobject is considered to be the object that the pointer points to.
Return value
Table 1 describes the return values of this built-in function when both of the following conditions are met.
- -O2 or higher optimization level is in effect.
- The objects that ptr points to can be determined at compile time.
If any of these conditions are not met, this built-in function returns the values as described in Table 2.
type | Return value |
---|---|
0 | The maximum of the sizes of all objects. The whole variable is considered to be the object that ptr points to. |
1 | The maximum of the sizes of all objects. The closest surrounding variable is considered to be the object that ptr points to. |
2 | The minimum of the sizes of all objects. The whole variable is considered to be the object that ptr points to. |
3 | The minimum of the sizes of all objects. The closest surrounding variable is considered to be the object that ptr points to. |
type | Return value |
---|---|
0 | (size_t) -1 |
1 | (size_t) -1 |
2 | (size_t) 0 |
3 | (size_t) 0 |
NoteIBM® XL C/C++ for Linux, V16.1 does not support the multiple targets and closest surrounding features. You can assign a value in the range 0 - 3 to type, but the compiler behavior is as if type were 0.
Examples
Consider the file myprogram.c:
#include "stdio.h"
int func(char *a){
char b[10];
char *p = &b[5];
printf("__builtin_object_size(a,0):%ld\n",__builtin_object_size(a,0));
printf("__builtin_object_size(b,0):%ld\n",__builtin_object_size(b,0));
printf("__builtin_object_size(p,0):%ld\n",__builtin_object_size(p,0));
return 0;
}
int main(){
char a[10];
func(a);
return 0;
}
- If you compile myprogram.c with the -O option, you get the following output:
__builtin_object_size(a,0):10 __builtin_object_size(b,0):10 __builtin_object_size(p,0):5
- If you compile myprogram.c with the -O and -qnoinline options, you get the following output:
__builtin_object_size(a,0):-1 /* The objects the pointer points to cannot be determined at compile time. */ __builtin_object_size(b,0):10 __builtin_object_size(p,0):5
Parent topic: