2010-04-08 58 views
0

我写了一个快速程序,在发出seg故障错误之前执行每个语句。执行完所有程序后在程序结束时发生seg故障?

struct foo 
{ 
    int cat; 
    int * dog; 
}; 

void bar (void * arg) 
{ 
    printf("o hello bar\n"); 
    struct foo * food = (struct foo *) arg; 
    printf("cat meows %i\n", food->cat); 
    printf("dog barks %i\n", *(food->dog)); 
} 
void main() 
{ 
    int cat = 4; 
    int * dog; 
    dog = &cat; 

    printf("cat meows %i\n", cat); 
    printf("dog barks %i\n", *dog); 

    struct foo * food; 
    food->cat = cat; 
    food->dog = dog; 

    printf("cat meows %i\n", food->cat); 
    printf("dog barks %i\n", *(food->dog)); 

    printf("time for foo!\n"); 
    bar(food); 
    printf("begone!\n"); 

    cat = 5; 
    printf("cat meows %i\n", cat); 
    printf("dog barks %i\n", *dog); 

// return 0; 
} 

赋予的

cat meows 4 
dog barks 4 
cat meows 4 
dog barks 4 
time for foo! 
o hello bar 
cat meows 4 
dog barks 4 
begone! 
cat meows 5 
dog barks 5 
Segmentation fault (core dumped) 

结果我真的不知道为什么它赛格末故障?任何意见/见解深表谢意。

回答

4

您正在取消引用无效内存的指针,food

行:

struct foo * food; 

声明食物是指向一个struct FOO。但是由于你没有初始化指针,它指向了你不拥有的未定义的内存区域。您可以只分配在堆栈上(注意,我已经改变了食物的类型):

struct foo food; 
food.cat = cat; 
food.dog = dog; 

printf("cat meows %i\n", food.cat); 
printf("dog barks %i\n", *(food.dog)); 

printf("time for foo!\n"); 
bar(&food); 

或使用malloc(保持类型结构FOO *):

struct foo * food = malloc(sizeof(struct foo)); 
if(food == NULL) 
    perror("Failed to allocate food."); 

以后你应该释放它(尽管在这种情况下,它没有多大意义):

free(food); 

有与程序的其他问题(如无效*参数),但是这解决了内存冲突。

+0

,如果你不介意的话,你能告诉我有关的其他问题(尤指一个约void *的参数,因为我碰巧使用非常频繁)。非常感谢! – 2010-04-08 06:00:15

+0

所以它会是 struct foo * food = malloc(sizeof(struct foo)); food =(struct foo *)arg; 在酒吧功能? 因为我仍然陷入seg故障。 – 2010-04-08 06:11:47

+0

哦等待愚蠢的愚蠢它的作品。非常感谢!! – 2010-04-08 06:15:06

1

那么,这些线路都出现了问题:

struct foo * food; 
food->cat = cat; 
food->dog = dog; 

食品是取消引用而不会被分配给任何一个指针。

struct foo food; 
food.cat = cat; 
food.dog = dog; 

可能会为您解决问题。

0

你得到未定义的行为,因为你没有malloc的食物结构。

1

您还没有一个结构变量分配空间,通过可变food指出:

struct foo * food; 

你需要做的:

struct foo * food = (struct foo*) malloc(sizeof(struct foo)); 

也曾经你是你应该重新分配该内存使用它完成:

free(food); 

替代你可以申报食物如为struct foo类型的变量:

struct foo food; // note the missing * 

然后可以访问使用->操作者的操作者.就地结构成员。所以

food->cat = cat; 

更改

food.cat = cat;