2017-03-27 145 views
0

我有一个错误,我无法找到一个方法来解决它。我得到这个错误运行程序时为什么会出现错误?

异常在 ConsoleApplication3.exe在0x504A3E6C(ucrtbased.dll)抛出:0000005:访问冲突读取位置 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(); 
} 
+3

您的意思是:'Expense * e = createExp(10,120,“Gaz”);'? –

+2

^你的编译器应该给出一个错误,如果你在标准符合模式下调用 –

+1

另外,这个assert(getType(e)==“Gaz”)断言并没有做你认为它正在做的事情。它总是会失败。 – AnT

回答

6

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

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

尝试Expense *e = createExp(10, 120, "Gaz");。大多数编译器应该给你一个警告,即在这种情况下使用单引号是不正确的。

还怀疑你的断言不是“按预期”assert(getType(e) == "Gaz"); - 应该不是一个strcmp()

+0

非常感谢。我解决了它! –

相关问题