C struct程序崩溃

时间:2014-04-29 20:52:04

标签: c struct

您好我正在尝试学习C.中的数据结构。我编写了一个程序,但是当我运行它时会崩溃

 #include <stdio.h>
 #include <stdlib.h>
 typedef struct{
         int x;
         int y;

        }structure; 
typedef struct{
        structure test1;
        }test;

void function(test *trying){
      trying->test1.x = 5; 

     printf("%d\n", trying->test1.x);

     }

int main(){
   test *mystruct;
   function(mystruct);
   system("pause");
   return 0;
}

谢谢!

6 个答案:

答案 0 :(得分:1)

test *mystruct;
function(mystruct);

mystruct指针未初始化且具有不确定的值。

由于缺少初始化,此语句调用未定义的行为:

trying->test1.x = 5; 

改为:

test mystruct;
function(&mystruct);

答案 1 :(得分:1)

当您撰写test *mystruct;时,mystruct包含垃圾值。如果此值位于程序的地址空间之外,则会出现错误。为何崩溃?因为它试图覆盖OS等受保护的内存区域。因此要么为mystruct分配内存并使用它(在这种情况下你必须释放内存)。或者普通声明为普通变量并将地址传递给函数。

test mystruct;
function(&mystruct);

答案 2 :(得分:0)

您可以使用此答案的后半部分,但正如其他评论者所指出的那样,将mystruct的地址简单地传递给该函数会好得多。

test mystruct;     // = (test *) malloc(sizeof(test));
function(&mystruct);

这意味着它是在堆栈上分配的,它与堆不同,并且您在使用它之后不必释放内存,因为它已经为您完成了。


如果您要将其声明为指针,则可以在堆上为test分配内存。

main中的第一行更改为:

test *mystruct = malloc(sizeof(test));

释放使用完毕后分配的内存:

free(mystruct);

答案 3 :(得分:0)

在函数main中,变量mystruct未初始化为指向有效的内存地址。因此,它很可能指向无效的内存地址,并且在函数function中使用时,最终会产生内存访问冲突。

修正建议#1:

test mystruct;
function(&mystruct);

修正建议#2:

test* mystruct = malloc(sizeof(test));
function(mystruct);
free(mystruct);

答案 4 :(得分:0)

如果您不想使用动态内存,请尝试以下操作:

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

typedef struct{
     int x;
     int y;
}structure; 
typedef struct{
    structure test1;
}test;

void function(test *trying){
    trying->test1.x = 5; 
    printf("%d\n", trying->test1.x);
}

int main(){
   test mystruct;
   memset(&mystruct, 0, sizeof(mystruct));
   function(&mystruct);
   system("pause");
   return 0;
}

这将创建一个基于堆栈的变量,并使用memset()函数初始化其内容。你有一个奇怪的中间typedef和成员,你可以完全消除。 e.g。

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

typedef struct my_s{
     int x;
     int y;
} my_t;

void function(my_t *t){
   if(!t) return;
   t->x = 5;
   printf("%d\n", t->x);
}

int main(){
   my_t mystruct;
   memset(&mystruct, 0, sizeof(mystruct));
   function(&mystruct);
   return 0;
}

最后,我不确定你要用系统完成什么(“暂停”)但是对于结构,上面的例子都可行。

答案 5 :(得分:0)

尝试对原始代码进行以下简单更改:(使用malloc()calloc()构建并运行

(在线评论解释)

#include <stdio.h>
 #include <stdlib.h>
 typedef struct{
         int x;
         int y;

        }structure; 
typedef struct{
        structure test1;
        }TEST; //use CAPITALS to distinguish typedefed struct for readability

TEST test;  //use typedef to create instance of TEST

void function(TEST *trying){
      trying->test1.x = 5; 

     printf("%d\n", trying->test1.x);

     }

int main(){
   TEST *mystruct; // create local instance of TEST

   mystruct = &test;//initialize mystruct pointer to point to beginning of physical struct
   function(mystruct);
   system("pause");
   return 0;
}