且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在其他文件的结构/数组上使用malloc

更新时间:2023-09-29 22:50:34

此行仅复制第一个三角形:

This line is copying only the first triangle:

*new->model = *model;

从函数的角度来看,model只是指向对象的指针.编译器不知道它指向三角形数组,因此我们需要将那里的三角形数量作为参数传递.

From the point of view of your function model is only a pointer to an object. The compiler doesn't know it points to an array of triangles, hence we need to pass the number of triangles in there as an argument.

替换为:

memcpy( new->model, model, sizeof(triangle_t)*numtriangles);

其他评论:

  • 记住,释放object
  • 时要释放model
  • 如果您考虑使用c ++编译器进行编译,请将new替换为newObj之类的东西
  • Remember to free the model when freeing the object
  • Replace new for something else like newObj if you ever consider to compile this with a c++ compiler

更多信息:

  • https://linux.die.net/man/3/memcpy
  • https://en.cppreference.com/w/c/string/byte/memcpy

关于分段错误:您的函数现在是正确的,除非内存不足,否则不会引起SEGFAULT,这是非常不可能的.无论如何,如果您的内存不足并在该函数中获取SEGFAULT,则问题可能是:

Regarding to the segmentation fault: your function is correct now and it is not causing SEGFAULT unless you are running out of memory, what is very unlikely. Anyway, if you are running out of memory and getting a SEGFAULT in that function then the problem is either:

  • 您没有在其他地方正确分配内存,然后内存泄漏使内存用尽不正确.
  • 您的平台需要更多的内存,尽管可能性不大,但可能会发生,尤其是在有限的嵌入式平台上

发布另一个带有段错误回溯的问题.

Post another question with the backtrace of the segfault.