繁体   English   中英

C struct程序崩溃

[英]C struct program crash

嗨我试图学习CI中的数据结构写一个程序,但它运行时崩溃

 #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;
}

谢谢!

test *mystruct;
function(mystruct);

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

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

trying->test1.x = 5; 

这样做:

test mystruct;
function(&mystruct);

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

test mystruct;
function(&mystruct);

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

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

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


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

更改你的第一线main以:

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

并释放使用它后分配的内存:

free(mystruct);

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

修正建议#1:

test mystruct;
function(&mystruct);

修正建议#2:

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

如果你不想使用动态内存,那么试试这个:

#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和成员,你可以完全消除。 例如

#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;
}

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

尝试对原始代码进行这些简单的更改:( 使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM