Dr.GV
Dr.GV

Reputation: 11

Impossible to use malloc and typedef

It seems that it is impossible to use typedef and incorporate a malloc function in my program: More specifically:

groups.h

#include "headers.h"
#include "info.h"
#include "sub_list.h"

typedef struct group_entity *group;

group new_group(int id);

void free_group(group group);

groups.c

#include "groups.h"

struct group_entity {
    int gId;
    info gFirst;
    info gLast;
    subinfo gSub;
};

group new_group(int id) {
    group new_group = malloc(sizeof(group));
    if (!new_group) {
        return NULL;
    }
    new_group->gId = id;
    new_group->gFirst = NULL;
    new_group->gLast = NULL;
    new_group->gSub = NULL;
    return new_group;
}


void free_group(group group) {
    free(group);
}

header.h

#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

#define MG 5 /* Length of Groups Array. */

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>

#include "headers.h"
#include "groups.h"
#include "info.h"
#include "sub_list.h"

int main() {
    group new_object = new_group(5);
    return 0;
}

Whenever I run this piece of code, I get halted with a breakpoint

exe_common.inl - ln 297.

    if (!has_cctor)
        _cexit();

I've tried using a free_group(group group) function in my main.c - but it seems that I hit a breakpoint. By using the VS 2019 debugger, I tried to find out which line causes the error. It seems that the breakpoint is caused AFTER my main is executed. Quite curious behavior, since main won't even return 0.

Upvotes: 0

Views: 118

Answers (2)

In addition to what KamilCuk said here, I would say that you can use a define directive in your groups.h file if your intent was to avoid to specify the * everytime.

typedef struct group_entity group;
#define *group GROUP_PTR
GROUP_PTR new_group(int id);

Then in your groups.c replace with the following:

GROUP_PTR new_group(int id) {
  GROUP_PTR new_group = malloc(sizeof(group));
  [...]
  return new_group;
}

It should work like a charm.

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141010

Typedef pointers are confusing. sizeof(group) is the size of the pointer not the size of the data. Consider using a typedef to the data, and adding * everywhere you are using a pointer, to indicate, clearly, that you are working with pointers.

typedef struct group_entity group;
group *new_group(int id);
void free_group(group *group);

group *new_group(int id) {
    group *new_group = malloc(sizeof(group));

Alternatively, you can do sizeof(*new_group) or sizeof(struct group_entity).

Upvotes: 5

Related Questions