C++函数传递指针面试题

【本文链接】

http://www.cnblogs.com/hellogiser/p/function-passing-pointer-interview-questions.html

【代码1】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
/*
version: 1.0
author: hellogiser
blog: http://www.cnblogs.com/hellogiser
date: 2014/10/8
*/


#include "stdafx.h"
#include <iostream>
using namespace std;

void GetMemory(char *p)
{
    p = (
char *)malloc(100);
}

void Test(void)
{
    
char *str = NULL;
    GetMemory(str);
    strcpy(str, 
"helloworld"); //str=NULL (RUNTIME ERROR)
    printf(str);
}

int main()
{
    Test();
    
return 0;
}

程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,"helloworld");将使程序崩溃。

【代码2】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
/*
version: 1.0
author: hellogiser
blog: http://www.cnblogs.com/hellogiser
date: 2014/10/8
*/


#include "stdafx.h"
#include <iostream>
using namespace std;

char *GetMemory(void)
{
    
char p[] = "helloworld";
    
return p; // on stack
}

void Test(void)
{
    
char *str = NULL;
    str = GetMemory();
    printf(str); 
//OK but ???
}

int main()
{
    Test();
    
return 0;
}

可能是乱码。因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不可知。

【代码3】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
/*
version: 1.0
author: hellogiser
blog: http://www.cnblogs.com/hellogiser
date: 2014/10/8
*/


#include "stdafx.h"
#include <iostream>
using namespace std;

void GetMemory(char **p, int num)
{
    *p = (
char *)malloc(num);
}
void Test(void)
{
    
char *str = NULL;
    GetMemory(&str, 
100);
    strcpy(str, 
"hello");
    printf(str); 
//ok, output hello
}

int main()
{
    Test();
    
return 0;
}

能够输出hello,但是内存泄漏

原文地址:https://www.cnblogs.com/hellogiser/p/function-passing-pointer-interview-questions.html