使用 printf 时出现段错误
我正在信号处理程序中针对浮点异常调试一些 Linux C 代码。 目标是检查浮点寄存器,打印一些信息,然后中止。 尝试打印 (char)('0' + phyreg)
的结果时出现分段错误。
struct ucontext * uc = (struct ucontext *) data;
fpregset_t fp = uc -> uc_mcontext.fpregs;
int top = (fp -> sw >> 11) & 0x07;
int i,j,k;
for (i = 0; i < 8; i++) {
static const char * tags [] = {
"valid", "zero", "invalid/infin", "empty"
};
int phyreg = (top + i) & 0x07;
struct _libc_fpreg* r = &(fp -> _st [phyreg]);
const char* regExp = (((r->exponent & 0x8000) != 0) ? "-" : "+");
printf (" FP %s: Mantissa= %s",
(char) ('0' + phyreg), // reg stack (SIGSEGV here)
regExp); // register exponent sign
j = (r->significand[3] >> 15) & 0x01;
printf ("%s.",(char) ('0' + j)); // mantissa (Also SIGSEGV here when
// previous SIGSEGV is commented out)
...
}
问题不是 (char)('0' + phyreg)
的计算,因为当我将其移动到单独的行并将结果存储在临时变量中时,我没有得到段错误,直到 printf 尝试显示 temp 变量。 那么,导致段错误的错误在哪里呢?
I am debugging some Linux C code in a signal handler for floating point exceptions. The goal is to check the floating point registers, print some information, and then abort. I get a segmentation fault when attempting to printf the result of (char)('0' + phyreg)
.
struct ucontext * uc = (struct ucontext *) data;
fpregset_t fp = uc -> uc_mcontext.fpregs;
int top = (fp -> sw >> 11) & 0x07;
int i,j,k;
for (i = 0; i < 8; i++) {
static const char * tags [] = {
"valid", "zero", "invalid/infin", "empty"
};
int phyreg = (top + i) & 0x07;
struct _libc_fpreg* r = &(fp -> _st [phyreg]);
const char* regExp = (((r->exponent & 0x8000) != 0) ? "-" : "+");
printf (" FP %s: Mantissa= %s",
(char) ('0' + phyreg), // reg stack (SIGSEGV here)
regExp); // register exponent sign
j = (r->significand[3] >> 15) & 0x01;
printf ("%s.",(char) ('0' + j)); // mantissa (Also SIGSEGV here when
// previous SIGSEGV is commented out)
...
}
It's not the calculation of (char)('0' + phyreg)
that's the problem, because when I move it to a separate line and store the result in a temp variable, I don't get the segfault until the printf tries to display the temp variable. So, where's the bug that causes the segfault?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在使用 %s 进行打印。 应为“ FP %c:尾数 = %s”。
You are printing with %s. Should be " FP %c: Mantissa = %s".
%s 表示一个字符串,你给它一个字符。 printf 将这个字符值解释为指向要打印的字符串的第一个字符的指针,这当然会失败。
将字符放入包含 2 个元素的字符数组中,第二个元素是 '\0',或者查看 printf 是否有计算结果为字符的内容。
%s means a string, you're giving it a character. This character value is interpreted by printf as a pointer to the first character of the string to print, which will of course fail horibbly.
Put the character into a character array with 2 elements, the second being '\0', or see if printf has something that evaluates to a character.
对单个字符使用
%c
格式说明符,而不是%s
(应该用于以null
结尾的字符串)。Use the
%c
format specifier for a single character, instead of%s
(which should be used for anull
-terminated string).