向NULL拷贝数据问题

C语言中NULL是0,0的地址是 0x00000000 受操作系统保护

所以直接向NULL拷贝是有问题的。要有合法的地址才行

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. void main1()
  6. {
  7. char *p1 = NULL; // p1默认地址是0x00000000 受操作系统保护
  8. /*
  9. 0x0FBD0A19 (ucrtbased.dll)处(位于 指针铁律1.exe 中)引发的异常: 0xC0000005: 写入位置 0x00000000 时发生访问冲突。
  10. 如有适用于此异常的处理程序,该程序便可安全地继续运行。
  11. */
  12. strcpy(p1, "abcdef123");
  13. printf("p1:%s\n", p1);
  14. system("pause");
  15. return 0;
  16. }
  17. void main2()
  18. {
  19. char *p1 = NULL; // p1默认地址是0x00000000 受操作系统保护
  20. /*
  21. 0x0F9A0A19 (ucrtbased.dll)处(位于 指针铁律1.exe 中)引发的异常: 0xC0000005: 写入位置 0x00000077 时发生访问冲突。
  22. 如有适用于此异常的处理程序,该程序便可安全地继续运行。
  23. */
  24. p1 = 0x00077;
  25. strcpy(p1, "abcdef123");
  26. printf("p1:%s\n", p1);
  27. system("pause");
  28. return 0;
  29. }
  30. // 正确的方式
  31. void main()
  32. {
  33. char *p1 = NULL; // p1默认地址是0x00000000 受操作系统保护
  34. p1 = (char *)malloc(100);
  35. strcpy(p1, "abcdef123");
  36. printf("p1:%s\n", p1); // p1:abcdef123
  37. system("pause");
  38. return 0;
  39. }

不断改变指针指向

C语言的精华

  1. void main()
  2. {
  3. int i;
  4. char buf[128]; // 在栈上分配内存
  5. char *p1 = NULL; // 在栈上
  6. char *p2 = NULL; // 在栈上
  7. p1 = &buf[0]; // 不断改变指针指向
  8. p1 = &buf[1];
  9. p1 = &buf[2];
  10. for (i = 0; i < 10; i++) {
  11. p1 = buf[i];
  12. }
  13. p2 = (char *)malloc(100);
  14. strcpy(p2, "abcde123654");
  15. for (i = 0; i < 10; i++) {
  16. p1 = p2+i;
  17. printf("%c ", *p1); // a b c d e 1 2 3 6 5
  18. }
  19. system("pause");
  20. return 0;
  21. }

铁律1-向NULL拷贝数据和不断改变指针指向 - 图1