- 论坛徽章:
- 1
|
本帖最后由 hanzhenlll 于 2012-11-01 13:10 编辑
我面试中遇到如下一个面试题.....
下面是一段有问题的代码 , 请诸位看看这段代码到底**问题?
为了好判断,我增加一些打印,输出结果如下...
------------------------- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void getmem (char *point)
- {
- printf ("Getmem point 0x%x, 0x%x\n", point, &point);
- if ((point = (char *)malloc (100)) == NULL)
- {
- printf ("malloc error !\n");
- // free NULL return
- }
- printf ("Getmem point 0x%x, 0x%x\n", point, &point);
- }
- int main (int argc, char *argv[])
- {
- char *p1 = NULL, *p2 = NULL;
- printf ("Init: p1 = 0x%x, 0x%x, p2 = 0x%x, 0x%x\n", p1, &p1, p2, &p2);
- p1 = (char *)malloc (100);
- printf ("Malloc: p1 = 0x%x, 0x%x\n", p1, &p1);
- strcpy (p1, "world");
- printf ("strcpy world --->%s \n", p1);
-
- getmem (p2);
- printf ("After p2 = 0x%x, 0x%x\n", p2, &p2);
- strcpy (p2, "hello");
- printf ("%s \n", p2);
- // free NULL
- return 0;
- }
复制代码 Init: p1 = 0x0, 0xbfdfd478, p2 = 0x0, 0xbfdfd47c
Malloc: p1 = 0x9648008, 0xbfdfd478
strcpy world --->world
Getmem point 0x0, 0xbfdfd450
Getmem point 0x9648070, 0xbfdfd450
After p2 = 0x0, 0xbfdfd47c
Segmentation fault (core dumped)
通过分析发现是 申请了新的栈地址后malloc, 入参本身并没有发生变化, 就如楼下所说的缘木求鱼,很形象;
getmem (p2); --> void getmem (char *point),这时候point 已经分配了新的栈地址,而后malloc后,point指向了新的堆区域, 但是p2本身并没有改,还是指向NULL..
解决的办法 1. getmem (&p2); void getmem (char **point);
2. char *getmem (char *point); 返回值申请后的堆地址..
|
|