c - 将数据从结构体插入 C 中的堆栈

标签 c data-structures segmentation-fault stack push

该程序的任务是使用memcpy 将结构中的所有数据压入堆栈。 执行时,它成功地将数据输入到结构中,但在执行 push() 函数时遇到了段错误。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <mem.h>

typedef struct STD {
   char ime [50];
   int fn;
   float usp;
   } STD;


 typedef struct STACK {
    STD *s;
    STACK *next;

    } STACK;
  int push (void *a, int siz,  STACK **sst) {
STACK *snew;
snew = (STACK *) malloc (siz + 1);
memcpy (snew->s, a, siz); 
 snew -> next = *sst;
 *sst = snew;


 }

int main () {
STACK *st;
STD  ss;

printf ("Vyvedi ime");
gets (ss.ime);
ss.ime[49] = 0;
printf ("Vyvedi fn");
scanf ("%d", &ss.fn);

printf ("Vyvedi usp");
scanf ("%f", &ss.usp);



push (&ss, sizeof(ss) , &st);



system ("pause");      }

不知道是否重要,我使用 DevC 作为编译器。

最佳答案

这段代码是错误的:

STACK *snew;
snew = (STACK *) malloc (siz + 1);
memcpy (snew->s, a, siz); 

snew->s 在您memcpy a 时未初始化。我希望看到两个 malloc - 一个用于 STACK*,另一个用于 STD*,然后您将使用它们来播种 snew->s 在将内容复制到其中之前。

STACK *snew;
snew = (STACK *) malloc (sizeof(STACK));
snew->s = (STD*) malloc(sizeof(STD));
memcpy (snew->s, a, siz);

或者,您可以使用单个 malloc,并将 snew->s 指向其中适当的偏移量(在为 STACK 留出空间之后结构).

STACK *snew;
snew = (STACK *) malloc (sizeof(STACK) + siz + 1);
snew->s = (char*)snew + sizeof(STACK);
memcpy (snew->s, a, siz);

push 函数中的siz 参数似乎是多余的,因为您总是传入一个struct STD

关于c - 将数据从结构体插入 C 中的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338701/

相关文章:

algorithm - 如何判断一个图是否是二分图?

c - 为客户端收到的消息出现段错误

C 程序。文件。

c - 了解 `int` 和 `long long` 变量的整数溢出

c - 下面的程序在比较字符串时异常终止,为什么?

c++ - 单链表插入和删除的时间复杂度

c++ - 在 Cairo Context 中创建智能指针时出现段错误

c - 如何在 C 代码中调用用 ARM 汇编语言编写的函数?

c - 如何更好地从指向某个地址的地址读取值

c - 警告 : format '%c' expects type 'int' , 但参数 2 的类型为 'char *'