Function returns invalid address

UPD: Okay, I’m sorry, but apparently example I provided was not enough to reproduce my error, that is why I’ll try to give more info on what I’m doing (I’m sorry again I thought it is same problem I have).
I’m developing "library" on c language and I want to initialize structure like this

// some_head.h
typedef struct phony phony;

phony* create_phony();
int action_on_phony(phony* target);
// some_head.c
#include "some_head.h"

typedef struct phony {
  GLFWwindow* window;
  int w, h;
} phony;

As I know, this way implementation of structure is hidden from user and he cannot access data in it, but still my library functions can work with it (some way of achieving encapsulation so to speak). So that’s why I have some create function(constructor):

// some_head.c
phony* create_phony()
{
    phony* created = malloc(sizeof(phony));
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    created->w = 1920;
    created->h = 1080;
    created->window = glfwCreateWindow(1920/2, 1080/2, "Later", NULL, NULL);
    if (created->window)
      glfwMakeContextCurrent(created->window);
    return created;
}

int action_on_phony(phony* target)
{
      return !glfwWindowShouldClose(target->window); // <- raises BAD_ACCESS
}

This works fine inside some_head.c, but when I’m trying to use this create_phony() thing somewhere else (ex. main()) like this:

#include "some_head.h"

int main()
{
    phony* obj = create_phony(); // <- gets invalid address
    action_on_phony(obj); 
    return 0;
}

It returns invalid address to me and I cannot pass it to other functions in some_head.c since they get invalid address and raise EXC_BAD_ACCESS when they try to work with this address.
I assume this comes due unknown implementation of phony struct (only some_head.c knows size of it after all), that main does not know what is this and makes this kind of thing. So my question is is there a way to properly return incomplete structure from some_head.c or find another way to encapsulate data inside phony structure?

>Solution :

  1. Your function does not have a return value.

This works fine inside some_head.c, but when I’m trying to use this
create_phony() thing somewhere else

  1. It is because the typedef of the struct should be in the .h file as well. Otherwise you have only forward declaration but compiler does not have any clue what is the size of this structure.

You need to have its declaration (prototype) in the .h file which has to be included in the code which calls this function.

phony *create_phony(void);

And then in a .c file its definition:

phony *create_phony(void)
{
    phony* obj = malloc(sizeof(*obj));
    if(obj)
    {  
        // init
    }
    return obj;
}

Notes:

  1. use objects not types in sizeofs.
  2. always check the result of malloc family functions.

Leave a Reply