假设我们有一个结构:
struct Person {
char *name;
};
struct Person *Person_create(char *name){
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
return who;
}
void Person_destroy(struct Person *who){
assert(who != NULL);
free(who->name);
free(who);
}
Run Code Online (Sandbox Code Playgroud)
主要功能:
int main(int argc,char *argv[]){
struct Person *mike = Person_create("mike");
Person_print(mike);
Person_destroy(mike);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有strdup()函数,上面的代码将无法正常工作.Valgrind说你试图免费提供的地址(who-> name)不是malloc'd.这背后的故事是什么,当我对结构体进行malloc化时,我没有对内存进行malloc吗?strdup()有什么不同?
在cplusplus.com参考文献中指出,在尝试生成随机数时使用模运算符会降低数字的可能性:
random_var = rand() % 100 + 1; //this will generate numbers between 1-100
Run Code Online (Sandbox Code Playgroud)
为什么较低的数字更可能?如果他们是,为什么我们不使用下面的代码:
random_var = rand()/(RAND_MAX/100) + 1; //also will generate those, more uniform I guess
Run Code Online (Sandbox Code Playgroud) 据我所知,我们可以在运行时或编译时创建对象.例如
SomeType object1;
SomeType *object2 = new SomeType;
Run Code Online (Sandbox Code Playgroud)
所以我认为在这里的代码;
int main(){
cout << "lalalal";
SomeType object1;
}
Run Code Online (Sandbox Code Playgroud)
应该为object1调用构造函数,然后lalalal应该出现在屏幕上.因为编译器在程序启动之前分配内存.那么在什么时候我错了?