Test/Test2/Test3/Test4(内存问题)

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4. #include <iostream.h>
  5. /*
  6.  * Test.cpp
  7.  *
  8.  *  Created on: Oct 22, 2008
  9.  *      Author: root
  10.  */
  11. char *GetMemory(void) {
  12.     char p[] = "hello world";
  13.     return p;
  14. }
  15. void Test(void) {
  16.     char *str = NULL;
  17.     str = GetMemory();
  18.     printf(str);
  19. }
  20. void GetMemory2(char *p) {
  21.     p = (char *) malloc(100);
  22. }
  23. void Test2(void) {
  24.     char *str = NULL;
  25.     GetMemory2(str);
  26.     strcpy(str, "hello world");
  27.     printf(str);
  28. }
  29. void Test3(void) {
  30.     char *str = (char *) malloc(100);
  31.     strcpy(str, "hello");
  32.     free(str);
  33.     if(str != NULL){
  34.         strcpy(str, "world");
  35.         printf(str);
  36.     }
  37. }
  38. void GetMemory4(char **p, int num) {
  39.     *p = (char *) malloc(num);
  40. }
  41. void Test4(void) {
  42.     char *str = NULL;
  43.     GetMemory4(&str, 100);
  44.     strcpy(str, "hello");
  45.     printf(str);
  46. }
  47. void testSizeOf(){
  48.     cout << endl << " sizeof(char) "<< sizeof(char) << endl;
  49.     cout << " ssizeof(int) "<< sizeof(int) << endl;
  50.     cout << " sizeof(unsigned int) "<< sizeof(unsigned int) << endl;
  51.     cout << " sizeof(long) "<< sizeof(long) << endl;
  52.     cout << " sizeof(unsigned long) "<< sizeof(unsigned long) << endl;
  53.     cout << " sizeof(float) "<< sizeof(float) << endl;
  54.     cout << " sizeof(double) "<< sizeof(double) << endl;
  55.     cout << " sizeof(void *) "<< sizeof(void *) << endl;
  56. }
  57. int main() {
  58.     //Test();
  59.     //Test2();
  60.     //Test3();
  61.     Test4();
  62.     testSizeOf();
  63.     return 0;
  64. }
 上面的代码来自高质量C++/C编程指南。

Test()的运行结果是未知,因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原现的内容已经在函数退出后被清除,新内容不可知。

Test2()的运行结果是程序崩溃。因为GetMemory2并不能传递动态内存(编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。传入的是一个指针,在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变),Test函数中的 str一直都是 NULL。strcpy(str, "hello world");将使程序崩溃。

Test4()的运行结果是hello。因为传入的是指针的指针,所以_p的改变,也就是改变传入的参数,故str被正确的复制。

Test3()的运行结果是输出world。篡改动态内存区的内容,后果难以预料,非常危险。因为free(str);之后,str成为野指针,但是str并没有置成空,所以if(str != NULL)语句不起作用。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值