内存分配的四个例子
原文在是:有关内存的思考题 在这篇基础上扩展了些知识,以做记录。
第一个例子:
char *GetMemory(char * p) { p = (char *)malloc(100); return p; } void Test(void) { char *str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str); }请问运行Test函数会有什么样的结果?
void Test(void) { char *str = NULL; str = GetMemory(str); strcpy(str, "hello world"); printf(str); }就对了,但是malloc的内存没有释放,有内存泄露问题。
char *GetMemory(void) { char p[] = "hello world"; return p; } void Test(void) { char *str = NULL; str = GetMemory(); printf(str); }请问运行Test函数会有什么样的结果?
char *GetMemory(void) { char *p = "hello world"; return p; }其他不变,这个Test函数运行的结果恒定为"hello world"。
char *p0 = "hello world"; char p1[] = "hello world"; *p0='W'; // 可以修改,因为p0指向的空间在栈上 *p1='W'; // 系统错误,因为试图修改文字常量区内容。这就是这个问题的本质区别。
第三个例子:
void GetMemory(char **p, int num) { *p = (char *)malloc(num); } void Test(void) { char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello world"); printf(str); }请问运行Test函数会有什么样的结果?
int get_x(int x, int *y) { x++; *y = x+1; return x; } void Test(void) { int x = 100; int y = 200; int z = get_x(x, &y); printf("x=%d y=%d z=%d\n", z, y,z); }输出结果为:x=100 y=102 z=101。
void Test(void) { char *str = (char *) malloc(100); strcpy(str, “hello”); free(str); if(str != NULL) { strcpy(str, “world”); printf(str); } }请问运行Test函数会有什么样的结果?
原文地址:http://blog.csdn.net/huibailingyu/article/details/43409573