【发布时间】:2017-03-27 01:02:21
【问题描述】:
我有一个错误,我找不到解决它的方法。我收到这个错误
在 0x504A3E6C (ucrtbased.dll) 处引发异常 ConsoleApplication3.exe: 0xC0000005: 访问冲突读取位置 0x0047617A。在第 11 行。
#include "Entities.h"
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
Expense* createExp(int nr_ap, float price, char* type) {
Expense *e = malloc(sizeof(Expense));
e->nr_ap = nr_ap;
e->price = price;
e->type = malloc(sizeof(char)*strlen(type) + 1); #Here is the problem.
strcpy(e->type, type);
return e;
}
void destroy(Expense *e) {
free(e->type);
free(e);
}
int getAp(Expense *e) {
return e->nr_ap;
}
float getPrice(Expense *e) {
return e->price;
}
char* getType(Expense *e) {
return e->type;
}
/*
Create a copy
*/
Expense *copyExp(Expense *e) {
return createExp(e->nr_ap, e->price, e->type);
}
void testCreateExp() {
Expense *e = createExp(10, 120, 'Gaz');
assert(getAp(e) == 10);
assert(getPrice(e) == 12);
assert(getType(e) == "Gaz");
destroy(e);
}
int main() {
testCreateExp();
}
【问题讨论】:
-
您的意思是:
Expense *e = createExp(10, 120, "Gaz");? -
^ 如果您在符合标准的模式下调用,您的编译器应该会给出错误提示
-
此外,这个断言
assert(getType(e) == "Gaz")并没有做你认为它正在做的事情。它总是会失败。 -
==比较的是两个char指针变量,而不是字符串本身,只有两个指针相同才会返回true,用
strcmp代替,并检查其返回值是否为0(即表示两个字符串相同)。 -
欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请查看About 页面以及How do I ask questions here? 和What do I do when someone answers my question?