C结构数组(抛出异常) [英] C array of structure (exception thrown)
问题描述
我创建了一个结构为Human的数组,该数组由 char * name
组成.
I have created an array of structure Human which consists of char *name
.
我使用这样的功能:
Human *createHuman(char *name){
Human *h = malloc(sizeof(Human));
h->name = strdup(name);
return h;
}
我已经测试了此功能,它可以正常工作,但是当我像这样使用它时,我的问题就开始了:
I have tested this function, it works perfectly, but my problem starts when i use it like this:
void gen_Humans(Human array[MAX], int n){
//n == max;
for (int i = 0; i<n; i++){
char *name = gen_name_function_used_before_WORKING();
array[i] = *createHuman(*name);
}
…
}
正如我说的,如果我产生一个人,那就很好了.我调试了代码,直到到达 strdup(name)
的地步时,它才给我:
As I said, if I generate one human it works just fine.
I debugged my code and when I got to the point of strdup(name)
it threw me this:
my error: Exception thrown at 0x53DCF6E0 (ucrtbased.dll) in project.exe:
0xC0000005: Access violation reading location 0x00000070.
我正在使用VS 2017 Enterprise.
I am using VS 2017 Enterprise.
推荐答案
添加到@MortizSchmidt的答案:
Adding to @MortizSchmidt's answer:
- 您没有检查
malloc()
的结果.即使失败的机会很小,您也应该这样做. - 您正在泄漏内存-因为您永远不会释放
malloc()
的内存,也不会将指针放在任何地方.请记住,C与Java不一样-赋值不是引用的赋值. - 请注意,函数签名中的
MAX
指示符没有任何作用.该参数是您可以通过任何方式编写的int *类型:int *数组
,int数组[]
或int数组[MAX]
.
- You are not checking the results of
malloc()
. You should do so, even if the chances of failure are small. - You are leaking memory - since you never free the
malloc()
ed memory nor do you keep the pointer anywhere. Remember C is not like Java - assignment is not an assignment of a reference. - Note that the
MAX
indicator in the function signature doesn't have any effect. The parameter is an int* any way you write it:int* array
,int array[]
orint array[MAX]
.
实际上,为什么还要分配Human结构而不是仅仅为字符串分配空间?
Actually, why even allocate the Human structure rather than just space for the string?
struct Human createHuman(char *name){
if (name == NULL) {
struct Human h = { NULL };
return h;
}
struct Human h = { strdup(name) };
if (h.name == NULL) { /* handle error here */ }
return h;
}
void gen_Humans(Human array[MAX], int n){
for (int i = 0; i < n; i++) {
char *name = gen_name_function_used_before_WORKING();
array[i] = createHuman(name);
}
…
}
这具有在将 name
设置为0之后将 Human
中的所有字段初始化的额外好处.
This has the added benefit of initializing all fields in Human
after name
to 0.
这篇关于C结构数组(抛出异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!