培训机构网站php源码,八戒logo设计网,支持ipv6网站开发,网站销售怎么推广文章目录 前言一、注意事项二、代码valgrind扫描总结 前言
在c语言中利用面向对象的编程方式#xff0c;实现类似c中的string类。 一、注意事项
所有与string结构体相关的函数全都没有返回值。 在c中#xff0c;当产生临时对象时编译器会自动的加入析构函数#xff0c;销毁… 文章目录 前言一、注意事项二、代码valgrind扫描总结 前言
在c语言中利用面向对象的编程方式实现类似c中的string类。 一、注意事项
所有与string结构体相关的函数全都没有返回值。 在c中当产生临时对象时编译器会自动的加入析构函数销毁临时变量但是C语言中必须手动显示的写出析构函数当string结构体相关函数返回临时变量时必须降临时变量显示赋值或者当场调用析构函数否则非常容易造成内存泄露。索性就都没有返回值。
二、代码
#include stdio.h
#include string.h
#include stdlib.h/*** 若对string相关函数提供返回值则非常容易造成内存泄露因此所有函数都不提供返回值
*/typedef struct _string
{char* ptr;int num;
} string;
void string_Ctor(string* s)
{memset(s, 0, sizeof(string));
}
void string_Dtor(string* s)
{free(s-ptr);memset(s, 0, sizeof(string));
}
void string_add(string* all, string s1, string s2)
{string sum; string_Ctor(sum);sum.num s1.num s2.num;sum.ptr (char*)malloc(sum.num 1);memcpy(sum.ptr, s1.ptr, s1.num);memcpy(sum.ptrs1.num, s2.ptr, s2.num);sum.ptr[sum.num] \0;string_Dtor(all);*all sum;
}
void string_assign_s_p(string* str, char* ptr)
{if (str-ptr ptr) return;string_Dtor(str);str-num strlen(ptr);str-ptr (char*)malloc(str-num1);memcpy(str-ptr, ptr, strlen(ptr));str-ptr[str-num] \0;
}
void string_assign_s_s(string* str1, string* str2)
{if (str1 str2) return;string_Dtor(str1);str1-num str2-num;str1-ptr (char*)malloc(str1-num 1);memcpy(str1-ptr, str2-ptr, str1-num);str1-ptr[str1-num] \0;
}
void string_add_assign(string* str1, string* str2)
{if (str1 str2) return;string sum; string_Ctor(sum);string_add(sum, *str1, *str2);string_Dtor(str1);*str1 sum;
}int main() {string http_head, http_body, http_msg;string_Ctor(http_head); string_Ctor(http_body); string_Ctor(http_msg);string_assign_s_p(http_head, abcdef);string_assign_s_p(http_msg, jskldfj;laskjdflkj);string_add_assign(http_msg, http_head);string_assign_s_s(http_body, http_msg);string_add(http_head, http_body, http_msg);printf(%s\n, http_head.ptr);string_Dtor(http_head); string_Dtor(http_body); string_Dtor(http_msg);
}
valgrind扫描
Valgrind——c/c内存检测工具
23054 Memcheck, a memory error detector
23054 Copyright (C) 2002-2017, and GNU GPLd, by Julian Seward et al.
23054 Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
23054 Command: ./a.out
23054 Parent PID: 18533
23054
23054
23054 HEAP SUMMARY:
23054 in use at exit: 0 bytes in 0 blocks
23054 total heap usage: 6 allocs, 6 frees, 1,149 bytes allocated
23054
23054 All heap blocks were freed -- no leaks are possible
23054
23054 For lists of detected and suppressed errors, rerun with: -s
23054 ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)总结
虽然可以利用面向对象的思想实现类似的c中的string类但是由于受到c语言语法的限制不能像写c一样写C如析构函数必须显示写出。