[关闭]
@w1024020103 2017-03-27T22:03:42.000000Z 字数 1619 阅读 570

discussion6 2 Breaking the System

CS61B


Below is the SNode class, along with a flawed implementation of the Stack ADT, BadIntStack.

  1. public class BadIntStack {
  2. public class SNode {
  3. public Integer val;
  4. public SNode prev;
  5. public SNode(Integer v, SNode p) {
  6. val = v;
  7. prev = p;
  8. }
  9. public SNode(Integer v) {
  10. this(v, null);
  11. }
  12. }
  13. public SNode top;
  14. public boolean isEmpty() {
  15. return top == null;
  16. }
  17. public void push(Integer num) {
  18. top = new SNode(num, top);
  19. }
  20. public Integer pop() {
  21. Integer ans = top.val;
  22. top = top.prev;
  23. return ans;
  24. }
  25. public Integer peek() {
  26. return top.val;
  27. }
  28. public static void main(String[] args) {
  29. BadIntStack trap = new BadIntStack();
  30. // Your exploit here
  31. while (!trap.isEmpty()) {
  32. trap.pop();
  33. }
  34. System.out.println("This print statement is unreachable!");
  35. }
  36. }

Fill in the Exploiter1 class so that it prints "Success!" by causing BadIntStack to produce a NullPointerException.

  1. class Exploiter1 {
  2. public static void main(String[] args) {
  3. try {
  4. // Your exploit here!
  5. BadIntStack newStack = new BadIntStack();
  6. newStack.pop();
  7. } catch (NullPointerException e) {
  8. System.out.println("Success!");
  9. }
  10. }
  11. }

Now, fill in the client class Exploiter2 so that it creates an "infinitely long" stack.

  1. class Exploiter2 {
  2. public static void main(String[] args) {
  3. BadIntStack trap = new BadIntStack();
  4. // Your exploit here!
  5. trap.push(new Integer(1));
  6. trap.top.prev = trap.top;
  7. while(!trap.isEmpty()) {
  8. trap.pop();
  9. }
  10. System.out.println("This print statement is unreachable!");
  11. }
  12. }

How can we change the BadIntStack class so that it won’t throw NullPointerExceptions
or allow ne’er-do-wells to produce endless stacks?

注意补上的一句

trap.top.prev = trap.top;

它的意思是:

8.JPG-14.8kB

像这样:

9.JPG-18.6kB

再回到原来的pop()方法的代码:

  1. public Integer pop() {
  2. Integer ans = top.val;
  3. top = top.prev;
  4. return ans;
  5. }

top = top.prev;

这句话不会对top造成任何影响,刚才的环形结构没被破坏,所以一直在运行while语句里的代码,没有办法执行print语句。

这道题让我想起最开始几堂课的disc3里的SNode,SList那一部分,有很多这类结构,可能并没有完全掌握,到了这儿又不会了。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注