简体   繁体   English

使用printf时的Segfault

[英]Segfault when using printf

I am debugging some Linux C code in a signal handler for floating point exceptions. 我正在为浮点异常的信号处理程序中调试一些Linux C代码。 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) . 尝试printf (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. 这不是(char)('0' + phyreg)的计算问题,因为当我将它移动到一个单独的行并将结果存储在临时变量中时,我不会得到段错误,直到printf尝试显示临时变量。 So, where's the bug that causes the segfault? 那么,导致段错误的错误在哪里?

You are printing with %s. 您正在使用%s打印。 Should be " FP %c: Mantissa = %s". 应为“FP%c:Mantissa =%s”。

%s means a string, you're giving it a character. %s表示一个字符串,你给它一个字符。 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. printf将此字符值解释为指向要打印的字符串的第一个字符的指针,这当然会失败。

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. 将字符放入包含2个元素的字符数组中,第二个元素为'\\ 0',或者查看printf是否具有评估字符的内容。

对单个字符使用%c 格式说明符,而不是%s (应该用于null终止字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM