C strcpy & memcpy & malloc & free
来源:互联网 发布:linux下编写python 编辑:程序博客网 时间:2024/06/16 18:07
strcpy
#include <stdio.h>#include <assert.h>#include <string.h>/*C语言标准库函数strcpy,把从src地址开始且含有'\0'结束符的字符串复制到以dest开始的地址空间。1 保护源字符串 用const2 空指针的检查3 返回 char * , 返回dst的原始值,实现链式表达式*/char *mystrcpy(char *dst , const char *src){ assert(dst != NULL && src != NULL); char *r = dst; while( (*dst ++ = *src ++) != '\0'); return r;}int main(){ char a[] = "12345"; char b[] = "aac"; //strcpy(b,a); // 错误,目标串长度小于源字符串长度 int len = strlen(mystrcpy(a, b)); printf("%d\n", len); printf("%s\n", a); printf("%s\n", b); return 0;}
C/C++——strcpy函数的 几种 实现 和 详细 解析
strcpy & memecpy
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ int i; char *ptr = malloc(10*sizeof(char)); ptr[0] = '1'; ptr[1] = '2'; ptr[2] = '\0'; char tmp[] = {'a', '\0', 'b'}; printf("%s %d\n",tmp, (int)strlen(tmp)); strcpy(ptr+2, tmp); //memcpy(ptr+2, tmp , 3); printf("%s\n",ptr); for(i = 0; i < 5 ; i++) { printf("%c\n", ptr[i]); } return 0;}
编译运行
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ int i; char *ptr = malloc(10*sizeof(char)); ptr[0] = '1'; ptr[1] = '2'; ptr[2] = '\0'; char tmp[] = {'a', '\0', 'b'}; printf("%s %d\n",tmp, (int)strlen(tmp)); //strcpy(ptr+2, tmp); memcpy(ptr+2, tmp , 3); printf("%s\n",ptr); for(i = 0; i < 5 ; i++) { printf("%c\n", ptr[i]); } return 0;}
再次编译运行
- strcpy 遇到’\0’ 就结束
- strlen 计算字符串长度时 也是遇到’\0’ 就结束
- memcpy 则不同,按照内存里面的内容复指定长度字节
malloc & free
#include <stdio.h>#include <stdlib.h>typedef struct node{ char *name; int sex;}student;student *stu_create(){ student *stu = (student *)malloc(sizeof(student *)); if(stu == NULL) return NULL; stu->name = NULL; stu->sex = 0; return stu;}stu_free(student *stu){ free(stu->name); free(stu); stu->name = NULL; stu = NULL;}int main(){ student *stu = stu_create(); stu->name = (char*)malloc(3); stu->name[0] = '1'; stu->name[1] = '2'; stu->name[2] = '\0'; printf("%x\n", stu); printf("%x\n", stu->name); printf("%s\n", stu->name); stu_free(stu); printf("%x\n", stu); printf("%x\n", stu->name); return 0;}
- free 里面 stu = NULL;是无效的
- 虽然stu内存空间释放了,但是stu并不指向NULL
如果free函数里面 stu->name != NULL ; 这句没有,那么stu->name内存释放了,但是stu->name不会指向NULL
这里只要没有stu = NULL;那么stu都是有地址的,但它的内存被销毁了
- 所以在free一个结构体后,接着的一条语句,就应该让该结构体指向NULL。
0 0
- C strcpy & memcpy & malloc & free
- C++ 指针的malloc、memcpy和 free
- C语言malloc\free
- C语言malloc/free
- C--malloc & free
- c语言strcpy和memcpy
- c memcpy 与 strcpy 区别
- C/C++:strcpy-strcnpy-memcpy-memmove
- C中的malloc和free
- C语言中 malloc/free
- c中的malloc和free
- c语言malloc和free
- C指针与malloc,free
- C中free和malloc
- C语言malloc和free
- c编码--指针/malloc/free
- C malloc free 函数实现
- C malloc & free 实际例子
- 读写锁
- Android 获取系统信息
- 说说堆及堆排序
- Genymotion Error in Ubuntu 14.04/ LTS
- CSS学习1(结构和层叠)
- C strcpy & memcpy & malloc & free
- Android应用组件
- 什么是Apple Pay?
- SQL Server:服务器角色
- 第十六周阅读程序-4
- The error occurred while setting parameters
- codeblocks中创建和调用静态链接库(lib)
- 如何测试两台电脑是否可以连接
- java中list、set和map 的区别