String series in practice c ++ -- do not use memset to initialize string (do not do this)
Baidu encyclopedia was so powerful for the first time:
Void * memset (void * s, int ch, size_t n );
Function explanation: Replace the first n Bytes (typedef unsigned int size_t) in s with ch and return s.
Memset: fills in a given value in a memory block. It is the fastest way to perform the clearing operation on a large struct or array.
Memset () functions are often used for memory space initialization:
char str[100]; memset(str,0,100);
It is used to set all memory space to a specific character. It is generally used to initialize the defined string'
memset(a, '\0', sizeof(a));
Memcpy is used for memory copying. You can use it to copy any data type object. You can specify the length of the copied data:
Char a [100], B [50]; memcpy (B, a, sizeof (B); // If sizeof (a) is used ), b's memory address overflows.
Strcpy can only copy strings. when it encounters '\ 0', it ends the copy:
char a[100], b[50];strcpy(a,b);
For example, if strcpy (B, a) is used, check whether the length of the string in a (before the first '\ 0') exceeds 50 bits. If it exceeds, this will cause memory address overflow of B.
Start as follows:
class Material{public: Material(){ setDefaults();} void setDefaults(){ memset(this,0,sizeof(*this));} int mark; char materialName[256]; // material name Vector3 ambient; // ambient Vector3 diffuse; // diffuse Vector3 specular; // specular int shininess; // float alpha; // bool isSpecular;char textureName[256]; // texture namechar textureTransName[256]; // transparent texture name};
This code is flawless. Let's take a look at the following:
class Material{public: Material(){ setDefaults();} void setDefaults(){ memset(this,0,sizeof(*this));} int mark; std::string materialName; // material name Vector3 ambient; // ambient Vector3 diffuse; // diffuse Vector3 specular; // specular int shininess; // float alpha; // bool isSpecular;std::string textureName; // texture namestd::string textureTransName; // transparent texture name};
The above code may cause memory leakage:
Therefore, for C ++ std: string, C ++-style Initialization is required.
When I see such a comment on the internet, I think it makes sense:
No memset can be used for any class. Once it is violent, it means that you have raped her internal data, and she has crashed.