检查通过malloc初始化的指针的值

时间:2019-03-29 07:49:56

标签: c

我正在尝试检查链表的头节点是否已填充正确的值。但是,指向该头节点的指针是使用malloc在另一个链接列表中初始化的,因此,该点的值是垃圾负数,但它不是NULL,因此请检查指针是否为NULL会失败。尝试访问此位置会导致内存冲突。如果malloc似乎首先给它分配了一些随机值,我该如何检查我是否真的将该指针分配给了任何东西?

相关的结构定义:

struct patient {
    char name[MAX_NAME];
    unsigned int roomNumber;
    struct doctor *doctors;     // linked list 'doctors' contains names of doctors
};

//  structure 'doctor' contains doctor's name 
struct doctor {
    char name[MAX_NAME];
    struct doctor *next;
};

初始化并添加患者:

void addPatient(char* patientNameInput, unsigned int roomNumInput)
{

    // Creating and initializing the patient:
    struct patientList *l;
    struct patient *p;
    p = (struct patient *) malloc(sizeof(struct patient)); // allocating memory safely
    l = (struct patientList *) malloc(sizeof(struct patientList));
. . .

相关代码:

void displayList(struct patientList* tempList)
{

    while (tempList) {
        printf("\nPatient name: %s\n", tempList->patient->name);
        printf("Room number: %i\n", tempList->patient->roomNumber);

        printf("Problem pointer: %i", tempList->patient->doctors); // this will always print a garbage value

        // Doctor stuff
        if (!tempList->patient->doctors) { // Always fails.
            printf("Doctors: N/A\n");
        }
        else {
            printf("Doctors: "); // this is the last thing to be displayed, before throwing a memory access violation exception
            struct doctor* dList = tempList->patient->doctors; // temp doc list
            while (dList->name) {
                printf("%s\n", dList->name);
                dList = dList->next;
            }
        }
        tempList = tempList->next;
    }

}

标有“总是失败”注释的行是我要检查的地方,实际上是在此处指定了医生类型,而不是它确实打印的垃圾值。如果此错误非常严重,我深表歉意。

0 个答案:

没有答案