tags:

views:

403

answers:

4

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

A: 

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.

Potatoswatter
I do have #include <stdlib.h>
Josh
+1  A: 

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).

Amit Kumar
I did comment //qsort(dastruct, len, sizeof(struct my_struct), cmp); and still same problem
Josh
@Josh: In that case your code is fine. There's nothing that can cause a segmentation fault in it. You either posting a fake code or incomplete code. Post the real code.
AndreyT
A: 

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).

Greg Hewgill
+1  A: 

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...)

AndreyT