1

I declare my struct in a header file like so:

typedef struct MyStruct{
    int test;
} MyStruct;

@interface StructTestingFile
MyStruct *originalStruct;
@end

Then from the .mm file, I call

originalStruct = loadTestInt();

In the C file, here is what I'm doing:

extern "C" MyStruct* loadTestInt()
{
    MyStruct *aStruct;

    aStruct->test = 1;

    return aStruct;
}

Every time it crashes on assigning aStruct->test = 1. What am I doing incorrectly?

1
  • I think it's because you're not allocating my struct. That first line in the C file creates which set to null, then you're trying to assign to null so you crash with a NullPointerException or something to that effect. Try calling malloc in that first line. Commented Mar 13, 2012 at 22:19

3 Answers 3

4

You're creating a pointer but not allocating memory for the struct itself;

MyStruct *aStruct;

aStruct = (MyStruct*)malloc(sizeof(MyStruct));

aStruct->test = 1;
Sign up to request clarification or add additional context in comments.

5 Comments

That makes sense and answers my question. However, I get an error saying Cannot initialize a variable of type "MyStruct*" with an rvalue of type "void*" ? Any ideas?
Try casting: aStruct = (MyStruct *)malloc(sizeof(MyStruct));
@karl_ Sorry, updated the answer, you'll need to cast the result of malloc to the correct type.
Yay Objective-C++. I'll retag the question to match.
Awesome, that did the track. I guess I've got to get better at reading compiler errors. Now that you pointed out the casting issue it seems glaringly obvious.
2

Dereferencing an uninitialized pointer causes undefined behaviour. aStruct doesn't point to anything when you do that assignment. Allocate some space, and you'll be off to the races:

extern "C" MyStruct* loadTestInt()
{
  MyStruct *aStruct = malloc(sizeof(MyStruct));
  aStruct->test = 1;
  return aStruct;
}

Comments

2

The other answers so far have pointed to the error of using pointers and not allocating memory.

However do you really want to use a pointer to your struct at all? A struct is a value-type (POD in C-ese), you can just pass them around the same as you would, say, an integer. Unless your structure is large, or identity is important (using identity to mean that two pointers refer to the exact same memory), dynamically allocating a struct is probably just work you don't need - especially as you have to free it later.

For comparison here is your code without pointers:

typedef struct MyStruct
{
   int test;
} MyStruct;

@interface StructTestingFile
{
   MyStruct originalStruct;
}
@end

And:

extern "C" MyStruct loadTestInt()
{
   MyStruct aStruct;

   aStruct.test = 1;

   return aStruct;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.