2017-03-27 170 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

非常感謝。我解決了它! –

相關問題