#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
void GetCharMemory(char **p, int num)
{
*p = (char*)malloc(sizeof(char) * num);
}
int main(void)
{
char *str = NULL;
GetCharMemory(&str, 100);
strcpy(str, "hello");
cout<<str<<endl;
free(str);
}
依次分析:
第一句 char *str = NULL; 定义字符指针str ,且str自身地址为:0x7fffffffe1d8,值为0x0。
(gdb) p &str
$1 = (char **) 0x7fffffffe1d8
(gdb) p str
$2 = 0x0
第二句 GetCharMemory(&str, 100); 将指针的地址和分配空间的大小传进去。
然后进入方法 GetCharMemory 中,此时形参char **p本身的地址为:0x7fffffffe1b8,p 的值等于传进来str的地址0x7fffffffe1d8,即p指向str。
p所指向的地址0x7fffffffe1d8的值即*p也是指针str的值仍为0x0。
(gdb) p &p
$3 = (char ***) 0x7fffffffe1b8
(gdb) p p
$4 = (char **) 0x7fffffffe1d8
(gdb) p *p
$5 = 0x0
然后这句 *p = (char*)malloc(sizeof(char) * num); 是给p所指向的str分配值。这个值是一块100个char类型大小的连续空间的首地址。再看此时*p的值:
(gdb) p *p
$6 = 0x602010 ""
分配空间后接下来给str指向的空间赋值 strcpy(str, "hello");,此时再看该地址的值:
(gdb) p &str
$7 = (char **) 0x7fffffffe1d8
(gdb) p str
$8 = 0x602010 "hello"
(gdb) p str+1
$9 = 0x602011 "ello"
上面可以看出指针str的值等于 GetCharMemory 方法分配的值,并且在str所指向地址(即str的值)对应的空间可以写入数据,同时该地址(0x602010)是分配后连续空间的首地址。