c++ - 函数不断覆盖以前的结构数据

标签 c++

<分区>

当我使用我的添加功能输入数据时,我可以毫无问题地打印它们。为 start(x,y), end(x,y) 添加一个 vaule 有效,我能够打印这些值。但是当我指定我想要两个 numGraphicElements 时函数在输入第一组开始值和结束值后离开。第二次循环时,它会覆盖我以前的值。

当我打印值时,它出于某种原因用随机数覆盖我的第一个值,然后只显示第二组开始(x,y)结束(x,y)值。

第一组的例子:开始(1,2)结束(3,4)....这个打印正确

添加了第二组示例:start(9,8) end (6,7)...这也打印

示例 pf 一起打印出 2 个集合,x(23424), y(653243), end = x(2334) y(33434).....x(9) y(8) end x(3) y(4).

#define _CRT_SECURE_NO_WARNINGS

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

#define _CRTDBG_MAP_ALLOC

enum
{
  RUNNING = 1
};

struct Point
{
  int x, y;
};

struct Line
{
  Point start;
  Point end;
};

struct GraphicElement
{
  enum
  {
    SIZE = 256
  };
  unsigned int numLines; //number of lines
  Line* pLines; //plines points to start and end
  char name[SIZE];
};

typedef struct
{
  unsigned int numGraphicElements;
  GraphicElement* pElements; //the head points to pLines
} VectorGraphic;

void InitVectorGraphic(VectorGraphic*);
void AddGraphicElement(VectorGraphic*);
void ReportVectorGraphic(VectorGraphic*);

VectorGraphic Image;

int main()
{
  char response;
  InitVectorGraphic(&Image);

  //for debugging purposes
  _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

  //main menu for the program
  while (RUNNING)
  {
    printf("\nPlease select an option:\n");
    printf("1. Add a Graphic Element\n");
    printf("2. List the Graphic Elements\n");
    printf("q. Quit\n");
    printf("CHOICE: ");
    fflush(stdin);
    scanf("%c", &response);

    switch (response)
    {
    case '1':
      AddGraphicElement(&Image);
      break;
    case '2':
      ReportVectorGraphic(&Image);
      break;
    case 'q':
      CleanUpVectorGraphic(&Image);
      return 0;
    default:
      printf("Please enter a valid option\n");
    }
    printf("\n");
  }
}

/*initialize the vectors, allocate memory*/
void InitVectorGraphic(VectorGraphic * pImage)
{ //addres of pImage is passed in
  struct GraphicElement *pElements;
  pImage->pElements = (GraphicElement*) malloc(sizeof(GraphicElement)); //pImage is now the addess of image
  pElements = (GraphicElement*) malloc(sizeof(GraphicElement));
  pImage->numGraphicElements = 8;
  pImage->pElements = NULL;
}

最佳答案

这里

line = (struct Line *) malloc(sizeof(Line));

代码恰好分配了一个行对象。

这里似乎要解决的不仅仅是 line[0]:

line[pImage->numGraphicElements]....

这样做代码会调用未定义的行为,从这一刻起任何事情都可能发生。这包括覆盖属于同一进程的其他内存。

关于c++ - 函数不断覆盖以前的结构数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678813/

相关文章:

c++ - 无法找到 -libboost_system

c++ - 如何在 C++ 中进行惰性构造?

c++ - 为什么在这个例子中有 "for(auto& x : v)"而不是 "for(auto x : &v)"?

c++ - 如果这个函数需要时间运行(小于peroid),我如何定期执行这个函数

c++ - C++中不同大小 vector 的迭代映射

c++ - Opengl VAO 被覆盖

c++ - 如何正确地从istream、ostream继承我的类?

c++ - 接受整数输入并返回字符串的函数

c++ - C++什么时候会出现Incomplete Type错误

c++ - 根据编译器优化和代码性能,`if constexpr` 与 `if`