为什么初始化结构时出现段错误? [英] Why I get segfault when initializing the struct?

查看:22
本文介绍了为什么初始化结构时出现段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索了大约一小时.我想我最好在这里发布问题.

Searched around for one hour. I guess I'd better post the question here.

我简化了代码.段错误在函数 initMyStruct 中.

I simplify the code. The segfault is in the function initMyStruct.

#include "stdlib.h"

typedef struct {
        int * arr1;
        int * arr2;
} myStruct;

void allocMyStruct (myStruct * a, int num) {
        a = malloc(sizeof(myStruct));
        a->arr1 = malloc(10*sizeof(int));
        a->arr2 = malloc(10*num*sizeof(int));
}
void initMyStruct (myStruct * a, int num) {
        int i;
        for (i = 0; i < 10; i++)     a->arr1[i]  =  0;
        for (i = 0; i < 10*num; i++) a->arr2[i]  = -1;
}
void freeMyStruct (myStruct * a, int num) {
        int i;
        for (i = 0; i < 10; i++)     free(a->arr1);
        for (i = 0; i < 10*num; i++) free(a->arr2);
        free(a);
}
int main (void) {
        int num = 3;
        myStruct * a;
        allocMyStruct (a, num);
        initMyStruct  (a, num);
        freeMyStruct  (a, num);
        return 1;
}

推荐答案

因为您没有保留指向新分配内存的指针,而是使用未初始化的指针并获得未定义的行为.

Because you're not keeping the pointer to the newly allocated memory, instead you use an uninitialized pointer and getting undefined behavior.

您将 a 变量传递给 allocMyStruct(),但该调用(与所有其他调用一样)按值,因此是新值在函数内部分配给它 not 会影响 main()a 的值.

You pass the a variable into allocMyStruct(), but that call is (like all others) by value, so the new value being assigned to it inside the function does not affect the value of a in main().

将其更改为 allocMyStruct() 要么返回新的指针值,要么获取指向该指针的指针.我更喜欢前者,它更简洁,使用函数返回值通常会带来更好的代码:

Change it so that allocMyStruct() either returns the new pointer value, or takes a pointer to the pointer. I would prefer the former, it's cleaner and using function return values often leads to better code:

myStruct * allocMyStruct(int num)
{
  myStruct *p;

  if((p = malloc(sizeof *p +
                 10 * sizeof *p->arr1 +
                 10 * num * sizeof *p->arr2)) != NULL)
  {
    p->arr1 = (int *) (p + 1);
    p->arr2 = p->arr1 + 10;
  }
  return p;
}

上面的代码还简化了内存分配,在一个大的 malloc() 调用中完成这一切,然后切片"成您实际需要的三个部分.

The above code also streamlines the memory allocation, doing it all in one big malloc() call which is then "sliced" into the three parts you actually need.

如果 arr1 的大小总是 10,那么动态分配它没有意义,它应该只是 int arr1[10]; 在结构声明.

If the size of arr1 is always 10 by the way, there's no point in having it dynamically allocated, it should just be int arr1[10]; in the struct declaration.

这篇关于为什么初始化结构时出现段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆