简体   繁体   English

如何强制 C 程序打印意外结果?

[英]How to force a C program to print an unexpected result?

The source code of square.c is: square.c的源代码是:

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

int square(int *ptr)
{
  int a;
  a = *ptr;
  return a * a;
}

int main(int argc, char **argv)
{
  int a, aa;
  srandom(time(NULL));
  a = random() % 10 + 1;
  aa = square(&a);
  printf("%d\n", aa);
  return 0;
}

The command-line to compile the source code is:编译源代码的命令行是:

gcc square.c -o square

Is it possible to run the square executable in Linux so that the printed value will not be a square of any integer number?是否可以在 Linux 中运行square可执行文件,以便打印的值不会是任何整数的平方?

Any method of running the program is allowed.允许任何运行程序的方法。

Yes.是的。 We can override printf.我们可以覆盖 printf。

Write the code in your post into square.c and compile it with gcc square.c将你帖子中的代码写入square.c并用gcc square.c编译

Make this file, fakesquare.c制作这个文件,fakesquare.c

int printf(char *str,int i)
{
    return puts("7");
}

Compile fakesquare.c as a shared library:将 fakesquare.c 编译为共享库:

gcc -fPIC -o libfakesquare.so -shared fakesquare.c

Run the square program with libfakesquare.so preloaded:运行带有 libfakesquare.so 预加载的 square 程序:

[15:27:27 0 /tmp] $ LD_PRELOAD=./libfakesqare.so ./a.out
7
[15:29:16 0 /tmp] $ LD_PRELOAD=./libfakesqare.so ./a.out
7
[15:29:16 0 /tmp] $ LD_PRELOAD=./libfakesqare.so ./a.out
7

Witout libfakeshared.so preloaded:没有 libfakeshared.so 预加载:

[15:29:40 0 /tmp] $  ./a.out
36
[15:29:41 0 /tmp] $  ./a.out
16
[15:29:42 0 /tmp] $  ./a.out
64

The only dependency at your code is libc.您的代码中唯一的依赖项是 libc。 If libc stays unmodified then your code will always work.如果 libc 保持不变,那么您的代码将始终有效。

Also your program will fail if before running it, all available memory is exhausted.此外,如果您的程序在运行之前,所有可用内存都已耗尽,它也会失败。 You can always check if ptr!=NULL.您可以随时检查 ptr!=NULL。

You could use this :你可以用这个:

Fastest way to determine if an integer's square root is an integer 确定整数的平方根是否为整数的最快方法

Their code seems optimized, but whichever is simplest should do the trick for you.他们的代码似乎优化了,但最简单的应该为您解决问题。

Assuming a standard C environment I don't see a reason why this should fail on a standard platform.假设一个标准的 C 环境,我看不出这在标准平台上失败的原因。 The code might fail if printf is not doing what it is inteded to do, but probably this is not what you are asking for.如果printf没有做它打算做的事情,代码可能会失败,但这可能不是你所要求的。 It also might fail on a platform where int is as small as a byte and a byte is only 6 bits wide.它也可能在int与一个字节一样小并且一个字节只有 6 位宽的平台上失败。 In this case your square function might calculate 9*9=81 which will not fit in the result type int (0..63 for 6 bit-byte).在这种情况下,您的平方函数可能会计算 9*9=81,这将不适合结果类型int (6 位字节为 0..63)。 But in my opinion this is a quite academic case.但在我看来,这是一个相当学术的案例。

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

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