2016-04-11 11 views
0

なぜこのエラーが発生するのか完全にはわからないため、単一の製品または製品の配列を使用しても同じ結果が得られます。構造体プロパティを参照する際のセグメンテーションフォールト(コアダンプ)

test.cの

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include "salesbase.h" 

//Function Declarations// 
struct Product new_product(int id, char name[120], float cost); 

int main(int argc, char *argv[]){ 
    struct Product testitem = new_product(0, "yes", 2.0); 
    printf("%f\n", testitem.product_cost); 
    getchar(); 
    return 0; 
} 

struct Product new_product(int id, char name[120], float cost){ 
    struct Product temp; 
    temp.product_id = id; 
    strcpy(name,temp.product_name); 
    temp.product_cost = cost; 
    temp.product_discount = 0.00; 
    return temp; 
} 

salesbase.h

#ifndef SALESBASE_H_ 
#define SALESBASE_H_ 

struct Product { 
    int product_id; 
    char product_name[120]; 
    float product_cost; 
    float product_discount; 
}; 
struct Sale { 
    int sale_id; 
    struct Product sale_items[100];  
}; 
#endif 
+7

'strcpyの(名前、temp.product_name)を変更;' 'strcpyの(temp.product_name、名)である必要があります。' – kaylum

+0

それは何かの値によって構造体を返すためにも少し珍しいですこのような。初期化される構造体へのポインタを渡す方がはるかに意味があります。そうすれば、不要な構造コピーを避けることができます。これはバグではなく、悪いデザインの選択肢です。 –

答えて

2

strcpyがそれに渡された不正なアドレスを取得しているように見えます。ここで

valgrind ./testの(関連)出力されます:

==21217== Conditional jump or move depends on uninitialised value(s) 
==21217== at 0x4C2DC8F: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==21217== by 0x400632: new_product (in /tmp/a.out) 
==21217== by 0x4005BE: main (in /tmp/a.out) 
==21217== 
==21217== 
==21217== Process terminating with default action of signal 11 (SIGSEGV): dumping core 
==21217== Bad permissions for mapped region at address 0x400734 
==21217== at 0x4C2DCAF: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==21217== by 0x400632: new_product (in /tmp/a.out) 
==21217== by 0x4005BE: main (in /tmp/a.out) 

たぶん引数nametemp.product_nameを交換してみてください。マニュアルページには、次の関数定義もあります:char *strcpy(char *dest, const char *src);

EDIT:一部の精度が

+0

これにvalgrindを使用してはいけません。そして、そうでないかもしれない。 –

+0

@jblixr将来のバグ修正のためのリソースを提供しています! –

関連する問題