Sometimes you will not get a runtime error when you access your array out of range in C code. such as:  char array[1024]; char* ptr = array; *(ptr-10) = 'a';  //or  *(ptr-4096) = 'a';   Assuming the array is on the stack, I am curious about what is the MIN SIZE that will let *(ptr-SIZE) = 'a' throw a segmentation fault in any situation?  for example:  *(ptr-4096*1024) = 'a' // this will always throw a segmentation fault *(ptr-4096*8) = 'a' // sometimes this will not throw a segmentation fault   2017/1/10, new added:  I feel sorry for not stating the question clearly. : (  What I want to know is not just a ambiguous UNDEFINED. Assuming the stack is high, and heap is low. So the memory layout will be:  high *********      * stack *  &lt;-  my array goes here      *********      *       *      *       *  &lt;-  ptr may be here      *       *      *********      * heap  *      *********      * ???   *  &lt;- ptr may be here      *********   Of course I know that     The problem is that C/C++ doesn't actually do any boundary checking with regards to arrays. It depends on the OS to ensure that you are accessing valid memory   So, the code above will cause the OS kernel invoke do_page_fault, and will try to find vma of the address, and check if the vma-&gt;vm_start &lt; address.   Now, let's come back to the question I asked: the MIN SIZE that will let *(ptr-SIZE) = 'a' throw a segmentation fault in any situation. In other word, I want to know the SIZE that the do_page_fault can afford. It is nothing about the C compiler, but how your OS protects your memory.
95859
Why does C/C++ differentiates in case of array index out of bound #include &lt;stdio.h&gt; int main() {     int a[10];     a[3]=4;     a[11]=3;//does not give segmentation fault     a[25]=4;//does not give segmentation fault     a[20000]=3; //gives segmentation fault     return 0; }  I understand that it's trying to access memory allocated to process or thread in case of a[11] or a[25] and it's going out of stack bounds in case of a[20000]. Why doesn't compiler or linker give an error, aren't they aware of the array size? If not then how does sizeof(a) work correctly?
86209
I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?  For example:      typedef struct     {         char *str;     } words;      main()     {         words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in.     }   Is this possible?    I've researched this: words* array = (words*)malloc(sizeof(words) * 100);  I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as:      words* array = (words*)malloc(sizeof(words));   However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment.    I've made a little progress however:      typedef struct {         char *str;     } words;      // Allocate first string.     words x = (words) malloc(sizeof(words));     x[0].str = "john";      // Allocate second string.     x=(words*) realloc(x, sizeof(words));     x[1].FirstName = "bob";      // printf second string.     printf("%s", x[1].str); --&gt; This is working, it's printing out bob.      free(x); // Free up memory.      printf("%s", x[1].str); --&gt; Not working since its still printing out BOB even though I freed up memory. What is wrong?   I did some error checking and this is what I found. If after I free up memory for x I add the following:      x=NULL;   then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC??    Thanks, I understand now due to:     FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith   Update  I'm trying to modularize and put the creation of my array of structs in a function but nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work? My code is as follows:      # include &lt;stdio.h&gt;     # include &lt;stdlib.h&gt;     # include &lt;string.h&gt;     # include &lt;ctype.h&gt;      typedef struct     {         char *str1;         char *str2;     } words;      void LoadData(words *, int *);      main()     {         words *x;         int num;          LoadData(&amp;x, &amp;num);          printf("%s %s", x[0].str1, x[0].str2);         printf("%s %s", x[1].str1, x[1].str2);          getch();     }//      void LoadData(words *x, int * num)     {         x = (words*) malloc(sizeof(words));          x[0].str1 = "johnnie\0";         x[0].str2 = "krapson\0";          x = (words*) realloc(x, sizeof(words)*2);         x[1].str1 = "bob\0";         x[1].str2 = "marley\0";          *num=*num+1;     }//   This simple test code is crashing and I have no idea why. Where is the bug?
22068
Why is Array.Length an int, and not a uint. This bothers me (just a bit) because a length value can never be negative.   This also forced me to use an int for a length-property on my own class, because when you  specify an int-value, this needs to be cast explicitly...  So the ultimate question is: is there any use for an unsigned int (uint)? Even Microsoft seems not to use them.
109558
Are these two equivalent?  char * aString = "This is a string.";  char aString[] = "This is a string.";  From my understanding, C++ stores strings by their addresses, so the pointer is getting a valid address. I assume the strings are also stored as type char? But how does it know how much memory to allocate for the string? Normally, char arrays need their array size preset. I believe the [] type arrays are counted by the compiler before compilation. Is this what happens for the string literal pointer as well?  On to my second question, what is the difference between these two:  int someNumber;  int * someNumber = new int;  The second is supposed to be dynamic allocation. If I understand the concept right, it allocates the memory as soon as it reads the declaration. But what happens in the standard declaration? Basically, I need to understand how dynamic allocation is advantageous over standard declarations.
46811
Is there any gcc option I can set that will give me the line number of the segmentation fault?  I know I can:   Debug line by line Put printfs in the code to narrow down.   Edits:   bt / where on gdb give No stack.
59948
I originally had an array[1..1000] that was defined as a global variable. But now I need that to be n, not 1000 and I don't find out n until later. I know what n is before I fill the array up but I need it to be global therefore need a way to define the size of a global array at run time.  Context is filling an array with a linear transformation of the bytes in a file.  I don't know how big the file is until someone wants to open it and the files can be of any size.
62317
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers.  To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values:  if (p &amp;&amp; !q)   do_something();   then using zero makes more sense (as in if you use NULL, you cannot logically use p &amp;&amp; !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL).  Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?  Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
119210
Is there a c++ equivalent of Java's  try {     ... } catch (Throwable t) {     ... }   I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing.  The native code appears fine in unit testing and only seems to crash when called through jni.  A generic exception catching mechanism would prove extremely useful.
112071
We had a discussion here at work regarding why fread() and fwrite() take a size per member and count and return the number of members read/written rather than just taking a buffer and size. The only use for it we could come up with is if you want to read/write an array of structures which aren't evenly divisible by the platform alignment and hence have been padded but that can't be so common as to warrant this choice in design. From :  The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.   The  function  fwrite()  writes  nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.   fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters).  If an error occurs, or  the end-of-file is reached, the return value is a short item count (or zero).
47168
I was trying to understand something with pointers, so I wrote this code:  #include &lt;stdio.h&gt;  int main(void) {     char s[] = "asd";     char **p = &amp;s;      printf("The value of s is: %p\n", s);     printf("The direction of s is: %p\n", &amp;s);      printf("The value of p is: %p\n", p);     printf("The direction of p is: %p\n", &amp;p);      printf("The direction of s[0] is: %p\n", &amp;s[0]);     printf("The direction of s[1] is: %p\n", &amp;s[1]);     printf("The direction of s[2] is: %p\n", &amp;s[2]);      return 0; }   When compiling it with gcc I get these warnings:  $ gcc main.c -o main-bin -ansi -pedantic -Wall -lm main.c: In function ‘main’: main.c:6: warning: initialization from incompatible pointer type main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’ main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’ main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’   (The flags for gcc are because I must be C89)  Why incompatible types of pointer? Isn't the name of an array a pointer to it's first element? So if s is a pointer to 'a', &amp;s must be a char **, no? And why do I get the other warnings? Do I have to cast the pointers with (void *) in order to print them?   And when running I get something like this:  $ ./main-bin The value of s is: 0xbfb7c860 The direction of s is: 0xbfb7c860 The value of p is: 0xbfb7c860 The direction of p is: 0xbfb7c85c The direction of s[0] is: 0xbfb7c860 The direction of s[1] is: 0xbfb7c861 The direction of s[2] is: 0xbfb7c862   How can the value of s and it's direction (and of course the value of p) be the same?
924
The following code receives seg fault on line 2:  char *str = "string"; str[0] = 'z';  // could be also written as *str = 'z' printf("%s\n", str);   While this works perfectly well:  char str[] = "string"; str[0] = 'z'; printf("%s\n", str);   Tested with MSVC and GCC.
11842
I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement makes code look very ugly.
88660
What is the accepted/most commonly used way to manipulate dynamic (with all dimensions not known until runtime) multi-dimensional arrays in C and/or C++.  I'm trying to find the cleanest way to accomplish what this Java code does:  public static void main(String[] args){  Scanner sc=new Scanner(System.in);  int rows=sc.nextInt();  int cols=sc.nextInt();  int[][] data=new int[rows][cols];  manipulate(data); }  public static void manipulate(int[][] data){    for(int i=0;i&lt;data.length;i++)    for(int j=0;j&lt;data[0].length.j++){          System.out.print(data[i][j]);           }     }   (reads from std_in just to clarify that dimensions aren't known until runtime).  Edit:I noticed that this question is pretty popular even though it's pretty old.  I don't actually agree with the top voted answer.   I think the best choice for C is to use a single-dimensional array as Guge said below "You can alloc rowscolssizeof(int) and access it by table[row*cols+col].".  There is a number of choices with C++, if you really like boost or stl then the answers below might be preferable, but the simplest and probably fastest choice is to use a single dimensional array as in C.  Another viable choice in C and C++ if you want the [][] syntax is lillq's answer down at the bottom is manually building the array with lots of malloc's.
25311
I've searched, but I've not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what's its real advantage? What are the problems of static and stack? Could I write an entire application without allocating variables in the heap?     I heard that others languages incorporate a "garbage collector" so you don't have to worry about memory. What does the garbage collector do?    What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?  Once someone said to me that with this declaration:  int * asafe=new int;   I have a "pointer to a pointer". What does it mean? It is different of:  asafe=new int;   ?
4478
As Joel points out in , in  (aka: K &amp; R), there is mention of this property of arrays in C: a[5] == 5[a]  Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]?
90586
Example C API signature:  void Func(unsigned char* bytes);  In C, when I want to pass a pointer to an array, I can do:  unsigned char* bytes = new unsigned char[1000]; Func(bytes); // call   How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?
5014
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.   Basically I have three questions:   Why use pointers over normal variables? When and where should I use pointers? How do you use pointers with arrays?