Josh
Josh

Reputation: 21

size of struct - size_t in c

For some reason I keep getting segmentation fault when I try to get the size of my struct.

struct my_struct {
  char *a;
  int  b;
};

int main(int argc, char *argv[])
{
    struct my_struct dastruct;
    size_t len = sizeof(dastruct) / sizeof(struct my_struct); // error
    qsort(dastruct, len, sizeof(struct my_struct), cmp);
    ...
}

Any ideas what I'm doing wrong? Thanks

Upvotes: 1

Views: 2347

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

If you are getting the crash specifically at the

size_t len = sizeof(dastruct) / sizeof(struct my_struct); 

line, it might be caused by sizeof(struct my_struct) evaluating to 0. (I.e the problem is actually the division by zero). This might happen in some compilers when type struct my_struct is incomplete, i.e. it is not defined. Using incomplete type in sizeof is illegal in C, but some compilers allow it for some reason, evaluating it to 0. (Although I'd expect the compiler to catch this division by 0 at compile time.)

Your code is obviously fake and doesn't illustrate the problem. If the above theory is correct, most likely in your real code you either mistyped the name of the type struct my_struct in sizeof or forgot to include the definition of the type struct my_struct.

(Highly unlikely, but anyway...)

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 994817

If your code as posted is your complete code, then you have failed to initialise the a pointer member of dastruct, so it's pointing off into some invalid location. When qsort() calls cmp() which presumably uses that pointer (you haven't shown that code), you are likely to get a segfault.

Note that I'm assuming your segfault happens at some place other than the initialisation of len that only divides two constants (which is likely to happen at compile time anyway).

Upvotes: 0

amit kumar
amit kumar

Reputation: 21052

You probably want to make dastruct an array.

   struct my_struct dastruct[10];

Edit: You've also not given cmp, so its not possible to say if something is wrong there (which I see would be the place the segmentation fault occurs).

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137950

The only thing I can possibly see is that you forgot to #include <stdlib.h>. Remember that C implicitly declares a qsort at the first use.

Upvotes: 0

Related Questions