执行一切后,在程序结束时出现故障?

时间:2010-04-08 05:38:22

标签: c segmentation-fault

我编写了一个快速程序,在发出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 个答案:

答案 0 :(得分:5)

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

该行:

struct foo * food;

声明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(将类型保持为struct foo *):

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

稍后你应该释放它(虽然在这种情况下它并不重要):

free(food);

程序还有其他问题(例如void *参数),但这解决了内存违规问题。

答案 1 :(得分:1)

嗯,这些行是个问题:

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

食物是一个指针,你可以在不指定任何东西的情况下取消引用。

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

可能会为你解决问题。

答案 2 :(得分: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;

答案 3 :(得分:0)

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

相关问题