i am creating a thread that will captures  packets and will store some information in a structure "flow" for each packet. i am using static array of "flow" type structures. but when i run the program it retuns SIGSEGV error. here's the structure "flow":  typedef struct flow {     unsigned int s_port;     unsigned int d_port;     char s_addr[20];     char d_addr[20];     int spi;     short total;      short data[10000];     struct timeval prev_t;     double ipt[10000];      flowParam info;     char status[100];  }flow;   note that flowParam is another structure whose object info is included in "flow". i also run program by commenting it but got same result...  and here's the main program:  int main() {     pthread_t tid;      int err = pthread_create(&amp;tid, NULL, Capture, NULL);         if (err != 0){             perror("\ncan't create capturing thread");             exit(-1);         }         else             printf("\nCapturing thread created!\n");      pthread_join(tid, NULL);     printf("Finished!!");     return 0; }  void* Capture() {     flow Register[5000]; /* flow Register */     //counter Counter[5000];      pthread_exit(NULL);  }   interestingly, when i use another structure "counter" and make its array in thread, it does not give such error.  typedef struct counter {     char s_addr[20];     char d_addr[20];     }counter;   i tried to my best to solve this issue but could not find any clue.any help???
1982
The following code is generating a stack overflow error for me  int main(int argc, char* argv[]) {     int sieve[2000000];     return 0; }   How do I get around this? I am using Turbo C++ but would like to keep my code in C  EDIT:  Thanks for the advice.  The code above was only for example, I actually declare the array in a function and not in sub main.  Also, I needed the array to be initialized to zeros, so when I googled malloc, I discovered that calloc was perfect for my purposes.  Malloc/calloc also has the advantage over allocating on the stack of allowing me to declare the size using a variable.
99144
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.  My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using gcc).  I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?
84371
In ANSI C, offsetof is defined as below.  #define offsetof(st, m) \     ((size_t) ( (char *)&amp;((st *)(0))-&gt;m - (char *)0 ))   Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?
84760
I am surprised that I can't initialize my fields in structs, why is it like that? Like:  struct MyStruct {     private int a = 90; }   but it's a complie time error. I don't know why it's a problem? Please explain this to me.
80355
I have this struct:  struct Map {     public int Size;      public Map ( int size )     {         this.Size = size;     }      public override string ToString ( )     {         return String.Format ( "Size: {0}", this.Size );     } }   When using array, it works:  Map [ ] arr = new Map [ 4 ] {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  arr [ 2 ].Size = 0;   But when using List, it doesn't compile:  List&lt;Map&gt; list = new List&lt;Map&gt; ( ) {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  list [ 2 ].Size = 0;   Why?
42535
If I have a class as follows     class Example_Class     {        private:          int x;           int y;         public:           Example_Class()           {               x = 8;              y = 9;          }        ~Example_Class()         { }     };   And a struct as follows  struct {    int x;    int y; } example_struct;   Is the structure in memory of the  example_struct simmilar to that in Example_Class  for example if I do the following  struct example_struct foo_struct; Example_Class foo_class = Example_Class();  memcpy(&amp;foo_struct, &amp;foo_class, sizeof(foo_struct));   will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ?  The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.  I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.
6378
I have a parameterised module in verilog, where the parameters are a clock rate and refresh rate, which is used to calculate how many cycles of inactivity are inserted between instances of a repeating operation.  However, it is very easy to set parameters that cannot be attained (because the operation takes a non-trivial length of time, so the repeat would have to occur before it had completed), and at the moment the design does not give any feedback on this.  I was wondering if there was some way I could trigger an error during synthesis (or compilation prior to simulation) if the conditions cannot be met (i.e. if one localparam is less than another)?  Some equivalent of the popular C/C++ compile-time-assert hack, perhaps.
32907
Are there any downsides to passing structs by value in C, rather than passing a pointer?  If the struct is large, there is obviously the performancd aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function.  It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that.  Are there any reasons for or against this?  Since it might not be obvious to everyone what I'm talking about here, I'll give  a simple example.  If you're programming in C, you'll sooner or later start writing functions that look like this:  void examine_data(const char *ptr, size_t len) {     ... }  char *p = ...; size_t l = ...; examine_data(p, l);   This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions.  But what happens when you want to return the same kind of information? You typically get something like this:  char *get_data(size_t *len); {     ...     *len = ...datalen...;     return ...data...; } size_t len; char *p = get_data(&amp;len);   This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function get_data isn't allowed to look at what len points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly.  So, the solution I propose is the simple struct  struct blob { char *ptr; size_t len; }   The examples can be rewritten like this:  void examine_data(const struct blob data) {     ... use data.tr and data.len ... }  struct blob = { .ptr = ..., .len = ... }; examine_data(blob);  struct blob get_data(void); {     ...     return (struct blob){ .ptr = ...data..., .len = ...len... }; } struct blob data = get_data();   For some reason, I think that most people would instinctively make examine_data take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much  clearer that they go together. And in the get_data case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length.
101459
I'm doing some polymorphic programming, and I decided that I wanted to be able to gracefully handle partial saves using SaveResult without blocking the user experience. The code looks roughly like this:  static void logDmlErrors(SObject[] src, SObject[] dest, SaveResult[] results, String message) {     // Transform results into Chatter error messages, send them to admins }   I then went about writing the utility methods that would use this function:  public static void insertRecords(SObject[] src, SObject[] dest, String message) {     logDmlErrors(src, dest, Database.insert(dest, false), message); }   Everything went well, until I came across the delete and undelete methods, which instead use DeleteResult and UndeleteResult. Both of those two classes contain the exact same methods as SaveResult, and yet don't appear to inherit from a common ancestor. This means that I can't just cast to a super-type to get to this information.  Thankfully, Summer 16 apparently introduced support for serializing (and deserializing) these classes as JSON, so I do have a fairly expensive (but accurate) workaround if I want proper polymorphic behavior, but I thought I'd throw it out there and see if someone has an alternative solution to this problem.
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
122083
A colleague of mine recently got bitten badly by writing out of bounds to a static array on the stack (he added an element to it without increasing the array size).  Shouldn't the compiler catch this kind of error?  The following code compiles cleanly with gcc, even with the -Wall -Wextra options, and yet it is clearly erroneous:  int main(void) {   int a[10];   a[13] = 3;  // oops, overwrote the return address   return 0; }   I'm positive that this is undefined behavior, although I can't find an excerpt from the C99 standard saying so at the moment.  But in the simplest case, where the size of an array is known as compile time and the indices are known at compile time, shouldn't the compiler emit a warning at the very least?
29225
I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronization, as the render loop needs to be pretty tight, and OSG itself tries to avoid having to ever lock. Most of the shared state is set before the thread is started, and never changed. I do have some data that does need to be changed, which I am planning to double-buffer. However, I have a simple boolean for signaling the thread to suspend rendering, and later resume rendering, and another to kill it. In both cases the app thread sets the bool, and the render thread only reads it. Do I need to synchronize access to these bools? As far as I can tell, the worse thing that could happen is the the render loop continues on for an extra frame before suspending or quitting.
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
13470
I am a little surprised by the following.  Example 1:  char s[100] = "abcd"; // declare and initialize - WORKS   Example 2:  char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)   I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
83512
In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?  Besides, my multidimensional array may contain types other than strings.
45967
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.  #include &lt;iostream&gt; #include &lt;vector&gt;  using namespace std;  int main() {     vector&lt;char&gt; deck;     char suit[] = {'h','d','c','s'};     char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};     for (int j=0; j&lt;13; j++) {         for (int i=0; i&lt;4; i++) {             deck.push_back(card[j] suit[i]);         }            }      return 0; }   I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
105267
Is it possible to dereference a void pointer without type-casting in the C programming language?  Also, is there any way of generalizing a function which can receive a pointer and store it in a void pointer and by using that void pointer, can we make a generalized function?  for e.g.:  void abc(void *a, int b) {    if(b==1)       printf("%d",*(int*)a);     // If integer pointer is received    else if(b==2)       printf("%c",*(char*)a);     // If character pointer is received    else if(b==3)       printf("%f",*(float*)a);     // If float pointer is received }   I want to make this function generic without using if-else statements - is this possible?   Also if there are good internet articles which explain the concept of a void pointer, then it would be beneficial if you could provide the URLs.  Also, is pointer arithmetic with void pointers possible?