【问题标题】:Why does an error occur when running the program?为什么运行程序时会出现错误?
【发布时间】: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?

标签: c pointers


【解决方案1】:

Expense *e = createExp(10, 120, 'Gaz'); 毫无意义。单引号用于单个字符,而不是 C 字符串。

例如char initial = 'G'; char* name = "Gaz";

试试Expense *e = createExp(10, 120, "Gaz");。大多数编译器都会警告您在这种情况下使用单引号是不正确的。

还怀疑您的断言不是“预期的”assert(getType(e) == "Gaz"); - 那不应该是strcmp() 吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多