【问题标题】:process structure memory allocation in CC中的进程结构内存分配
【发布时间】:2011-11-12 22:53:46
【问题描述】:

编辑:

Typedef struct SPro{
     int arrivalTime;
     char processName[15];
     int burst;
} PRO;

我有一个 PRO 类型的数组

PRO Array[100];
PRO enteringProcess;
//initialize entering process

然后我需要创建一个新进程并使用 malloc 为该进程分配内存然后将数组中的指针指向 malloc 返回的内存块。

PRO *newPro = (PRO *) malloc (sizeof(PRO));
newPro = enteringProcess;
ProArray[0] = *newPro;

似乎我做错了什么,因为我的程序在运行时崩溃了。 有什么帮助吗?谢谢!

【问题讨论】:

  • 程序在哪里崩溃?在上面的代码中? PRO是如何定义的?对不起,但对我来说,上面的 sn-ps 包含的信息太少了。
  • entertingProcess 是如何声明的?也是指针吗?
  • 即使在编辑之后我也很迷茫和困惑 :) 该睡觉了...
  • 我想多看看你的代码会很有用,或者至少知道你认为程序在哪里崩溃。但据我所见,“newPro = enterProcess;”已经有问题了陈述。这个“enteringProcess”变量是什么?因为在下一个语句中,您要取消引用“newPro”,它实际上是“enteringProcess”。此外,“ProArray”是“PRO”数组而不是“PRO*”数组,这似乎是您真正想要的。同样,欢迎提供更多详细信息。
  • 最好发布实际编译的代码,而不是 Q 中错误复制的代码。请为此使用剪贴板。

标签: c arrays malloc structure


【解决方案1】:

为什么需要分配内存,声明

  PRO Array[100];

已经分配了内存——假设你对 PRO 的定义是这样的;

  typedef struct {
     .....
  } PRO;

审查您的代码;

// Declare a new pointer, and assign malloced memory
PRO *newPro = (PRO *) malloc (sizeof(PRO));

// override the newly declared pointer with something else, memory is now lost
newPro = enteringProcess;

// Take the content of 'enteringProcess' as assigned to the pointer, 
// and copy the content across to the memory already allocated in ProArray[0] 
ProArray[0] = *newPro;

你可能想要这样的东西;

  typedef struct {
     ...
  } PRO;

  PRO *Array[100]; // Decalre an array of 100 pointers;

  PRO *newPro = (PRO *) malloc (sizeof(PRO));
  *newPro = enteringProcess;  // copy the content across to alloced memory
  ProArray[0] = newpro; // Keep track of the pointers

【讨论】:

    【解决方案2】:

    您似乎需要一个指向 PRO 的 指针 数组:

    PRO *Array[100];
    
    PRO *newPro = (PRO *) malloc (sizeof(PRO));
    /* ... */
    Array[0] = newPro;
    

    我不知道enteringProcess 是什么,所以我不能发表意见。只是你不应该给newPro分配任何东西,除了malloc的返回,否则你会泄漏新对象。

    【讨论】:

    • 为什么是指针数组?赋值 Array[0] = *newPro 将 newPro 指向的地址的值复制到变量 Array[0] 中。这个分配是正确的。
    • 语法正确,但毫无意义。创建一个动态对象只是为了将其用作分配的来源?如果这是您的需要,您应该使用自动(又名本地)变量。或者更好的是,直接将对象初始化到数组中。我的猜测是,如果他使用malloc 是因为他需要对象是动态的。
    • 我同意,代码有点混乱。正如我在回答中所说,我没有看到 newPro 指针的意义。
    【解决方案3】:

    我猜 enterProcess 指向了内存中的一个无效位置。

    newPro = enteringProcess
    

    是你的问题。

    【讨论】:

      猜你喜欢
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多