2014-11-23 54 views
0

我有一個函數爲某個數組創建一個副本。我的代碼的結構是:斷言在memcpy之後失敗c

typedef struct { 
    int* data; 
    unsigned int len; 
} intarr_t; 

我寫的功能是:

intarr_t* intarr_copy(const intarr_t* ia) 
{ 
    unsigned int len; 
    intarr_t* newia = malloc(sizeof(intarr_t)); 
    assert (newia); 
    newia->data = malloc(sizeof(int)*len); 
    newia->len = len; 
    if (newia == 0) 
    { 
     return NULL; 
    } 
    else 
    { 
     memcpy (newia->data, ia->data, len*sizeof(int)); 
    } 
    return 0; 
} 

當我測試的功能,它停止了我的功能,說我對IA斷言失敗。我唯一的地方是使用memcpy。但我甚至沒有在我的功能上做出斷言。有人知道爲什麼它給了我一個斷言錯誤?

+0

原因可能是你永遠不會將你的'len'變量初始化爲一個值。很可能你真的想要做一些像'unsigned int len = ia-> len;' – 2014-11-23 08:54:47

+0

len的未初始化。也儘量保持你的代碼的連貫性,而不是混合。 'NULL','0'等等,如果你真的是指同一件事。另一件事是,如果'newia'被正確地分配,並且隨後用if語句檢查它,則斷言。我真的不知道這個代碼甚至應該做什麼,因爲你根據len值複製隨機數據量... – 2014-11-23 08:55:55

+0

'unsigned int len = ia-> len;'和intXXX_t是系統保留名稱。 – BLUEPIXY 2014-11-23 08:57:57

回答

1

你看到一個崩潰的原因是:

memcpy (newia->data, ia->data, len*sizeof(int)); 

在這一行的len的價值是不確定的,所以你看到一個崩潰。 另外我們看到len正在被初始化,並且在不正確的函數的多個位置被使用,因爲len的值在沒有初始化的情況下將是不確定的。

此外,還有很多東西在代碼中是多餘的。

檢查內存分配成功或失敗只是調用malloc()後

intarr_t* newia = malloc(sizeof(intarr_t)); 

if(newia == NULL) 
{ 
printf("Memory allocation failed\n"); 
return; 
} 

因此,通過這樣做,你不是在訪問無效的內存。

接下來,您的命名約定太差。你必須有可讀的typedef,不像 intarr_t

+0

@MattMcNabb感謝您注意到我更新了我的答案。 – Gopi 2014-11-23 09:23:31

0
// the following is assuming that 'len' is the number of ints in the memory 
// pointed to by 'data' 
// I would strong suggest you use variable names that indicate 
// if something is a pointer 
// (typically by pre-pending 'p' 
// and capitalizing the first letter of the rest of the variable name) 

intarr_t* intarr_copy(const intarr_t* ia) 
{ 

    intarr_t* newia = malloc(sizeof(intarr_t)); 

    if(NULL == newia) 
    { // then, malloc failed 
     perror("malloc failed for intarr_t")' 
     exit(EXIT_FAILURE); 
    } 

    // implied else, malloc for intarr_t successful 

    newia->data = malloc(sizeof(int)*ia->len); 

    if(NULL == newia->data) 
    { // then malloc failed 
     perror("malloc failed for int array"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, malloc of data array successful 

    // set fields in newia 
    newia->len = ia->len; 
    memcpy (newia->data, ia->data, (sizeof(int)*ia->len)); 

    return(newia); 
}