我希望计算程序的bss部分和堆部分的开始之间的距离,所以我有一个这样的程序:
$ cat 1.cpp
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int empty;//bss
int main()
{
char*p=(char*)malloc(0);
printf("%d\n",(int)p-(int)&empty);
return 0;
}
当我使用以下代码编译代码时
$ g++ 1.cpp
错误是:
1.cpp: In function ‘int main()’:
1.cpp:8:22: error: cast from ‘char*’ to ‘int’ loses precision [-fpermissive]
printf("%d\n",(int)p-(int)&empty);
^
1.cpp:8:30: error: cast from ‘int*’ to ‘int’ loses precision [-fpermissive]
printf("%d\n",(int)p-(int)&empty);
^
我认为将int*
转换为int
并不合适。我在互联网上找到了大量的例子。
为什么我的代码没有编译?
答案 0 :(得分:3)
不要总是信任您在互联网上阅读的内容。
据推测,你是在一个指针为64位且int
为32位的平台上。在这种情况下,从指针到uintptr_t
的转换会失去精度,并且您正在使用正确的标志进行编译以使其成为错误。做得好!
您要将指针转换为整数类型的类型为// "self" in here is an UIView that contains some images inside.
{
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *blurredEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
CGRect frame = self.frame;
frame.origin = CGPointMake (0, 0);
blurredEffectView.frame = frame;
[self addSubview:blurredEffectView];
UIView *maskView = [[UIView alloc] initWithFrame:frame];
maskView.backgroundColor = [UIColor blackColor];
__weak UIView *weak = self;
maskView.layer.mask = ({ // This mask draws a rectangle and crops a circle inside it.
__strong UIView *strong = weak;
CGRect roundedRect = CGRectMake (
0,
0,
strong.frame.size.width * 0.8f,
strong.frame.size.width * 0.8f
);
roundedRect.origin.x = strong.frame.size.width / 2 - roundedRect.size.width / 2;
roundedRect.origin.y = strong.frame.size.height / 2 - roundedRect.size.height / 2;
CGFloat cornerRadius = roundedRect.size.height / 2.0f;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
UIBezierPath *croppedPath = [UIBezierPath bezierPathWithRoundedRect:roundedRect cornerRadius:cornerRadius];
[path appendPath:croppedPath];
[path setUsesEvenOddFillRule:YES];
CAShapeLayer *mask = [CAShapeLayer layer];
mask.path = path.CGPath;
mask.fillRule = kCAFillRuleEvenOdd;
mask;
});
blurredEffectView.maskView = maskView;
}
。这由标准定义为具有足够的宽度以允许无损转换。
答案 1 :(得分:1)
从指针转换为的类型应为uintptr_t,保证不会丢失精度,另请参阅fixed width integer types。
如果你坚持使用printf,那么你需要找到合适的格式化程序,因为这不是固定的。否则,请使用:
std::cout << reinterpret_cast<uintptr_t>(p);
答案 2 :(得分:1)
您可能需要p-reinterpret_cast<char*>(&empty)
但我认为没有理由计算两个地址之间的距离。 (并且是@mch所指出的未定义的行为)