how can I write code to test a[100];

This is a discussion on how can I write code to test a[100]; within the C Programming forums, part of the General Programming Boards category; I write some codes as follows: Code: int main() { int a[2]; a[0] = 1; a[1] = 1; return 0; ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    168

    how can I write code to test a[100];

    I write some codes as follows:
    Code:
    int main()
    {
      int a[2];
      a[0] = 1;
      a[1] = 1;
      
      return 0;
    }
    If my printing code is as follow:
    Code:
    printf("%d\n",a[100]); //a[100] not defined
    The result is "segmentation fault";

    how can I write code to test a[100];
    (I means if a[100] is defined, print
    if a[100] is not defined, printf("a[100] is not defined.\n")

    how can I come true?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Look at the C library pages for sizeof();

    And... please don't start multiple threads for the same question... the mods here don't like it.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    C doesn't keep you from wandering around in memory you shouldn't be wandering in. You have to do that yourself.

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    To find how many elements are in an array you can use...

    Code:
    // declare array
    int array[100];
    int sarray;
    
    // how many elements?
    sarray = (sizeof(array) / sizeof(array[0]));
    BUT... this only works for static arrays, it's not going to work with arrays created with mallloc. Those you have to keep track of yourself. Quzah is exactly correct... C doesn't prevent buffer overruns or attempting to read/write data outside of array bounds.

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by CommonTater View Post
    Look at the C library pages for sizeof();

    And... please don't start multiple threads for the same question... the mods here don't like it.
    It's my mistake for starting multiple threads for the same question!

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by quzah View Post
    C doesn't keep you from wandering around in memory you shouldn't be wandering in. You have to do that yourself.

    Quzah.
    I see!

    my means is that how to test one data structure whether be defined.( how to test the data which will be printed whether is out of memory )
    Code:
    char *string =  (char*) malloc ( 100*sizeof(char));
    
    // 1000 is my on purpose, though 100 is defined.
    for ( int i = 0; i < 1000; ++i )
    {
            //my test code is that,but I don't know whether is right
             if ( string[i] )
             {
                       printf("%c,",string[i]);
             } else
             {
                        printf("error of memory.\n"); exit(1);
              }
    }
    Last edited by zcrself; 12-22-2010 at 06:27 PM.

  7. #7
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by CommonTater View Post
    To find how many elements are in an array you can use...

    Code:
    // declare array
    int array[100];
    int sarray;
    
    // how many elements?
    sarray = (sizeof(array) / sizeof(array[0]));
    BUT... this only works for static arrays, it's not going to work with arrays created with mallloc. Those you have to keep track of yourself. Quzah is exactly correct... C doesn't prevent buffer overruns or attempting to read/write data outside of array bounds.
    thanks for your answer. It is good for me.

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by quzah View Post
    C doesn't keep you from wandering around in memory you shouldn't be wandering in. You have to do that yourself.

    Quzah.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    char*  fillData()
    {
            char *fd = (char*) malloc ( 100*sizeof(char));
            for ( int i = 0; i < 100; ++i )
            {
                    fd[i] = 'A';
            }
            return fd;
    }
    char** createTwoDimArray()
    {
            char **ptr = (char**) malloc ( 100 * sizeof(char*) );
            for ( int i = 0; i < 100; ++i )
            {
                    *(ptr+i) = fillData();
            }
            return ptr;
    }
    void print(char **p)
    {
            for ( int i = 0; i < 1000; ++i )
            {
                    printf("line:%d\n",i);
                    for ( int j = 0; j < 1000; ++j )
                    {
                            if( p[i][j] != NULL ) { printf("%c,",p[i][j]); }else { break; }
                    }
                    printf("\n");
            }
    }
    int main()
    {
                  char **p = createTwoDimArray();
                  print(p);
    
                   return 0;
    }
    why segmentation fault?
    1000 can not be modified. It's written on purpose
    How to modify the red codes to skip this error? ( how to identify the overruns? )
    Last edited by zcrself; 12-22-2010 at 10:17 PM.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    With just having a pointer, you can't know where you're allowed to go from there.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,546
    There is no way for a program to identify down to the byte level whether a particular memory access constitutes an array overrun.

    Lets say your OS has a page size of 1K. When you do a particular memory allocation, you get a pointer to the start of a page, so
    char *p = malloc(100);

    1. The valid subscripts are 0 to 99.
    2. Anything from 100 to 1023 is an array overrun, but the OS doesn't care as it is still within the same page.
    3. But try p[1024], and that would be a reference to another page - one that doesn't exist. At that point, you get your segfault.

    Tools like valgrind and electric fence can help you to locate a lot of case 2.

    You could also use man page sigaction section 2 to write a handler for the segfault, though what you could do about it is debatable. You certainly couldn't just ignore it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    msh
    msh is offline
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Tell us what the actual assignment is and we'll tell you what you're doing wrong. I'm assuming it is one of the "here's a function, now write the rest of the program" variety, but we need to know the actual conditions to help you.
    Disclaimer: This post shows my ignorance at the time of its making. I claim ownership of but not responsibility for all errors in it. Reference at your own peril.

  12. #12
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by Salem View Post
    There is no way for a program to identify down to the byte level whether a particular memory access constitutes an array overrun.

    Lets say your OS has a page size of 1K. When you do a particular memory allocation, you get a pointer to the start of a page, so
    char *p = malloc(100);

    1. The valid subscripts are 0 to 99.
    2. Anything from 100 to 1023 is an array overrun, but the OS doesn't care as it is still within the same page.
    3. But try p[1024], and that would be a reference to another page - one that doesn't exist. At that point, you get your segfault.

    Tools like valgrind and electric fence can help you to locate a lot of case 2.

    You could also use man page sigaction section 2 to write a handler for the segfault, though what you could do about it is debatable. You certainly couldn't just ignore it.
    I like this answer. It is better

  13. #13
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by msh View Post
    Tell us what the actual assignment is and we'll tell you what you're doing wrong. I'm assuming it is one of the "here's a function, now write the rest of the program" variety, but we need to know the actual conditions to help you.
    Sometimes, when my program runs, there is a error "segmentation error", but I don't know why and where is the error. I want to handle this error, but I don't know how to do handling.

    Do you understand my meaning?

  14. #14
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    454
    Quote Originally Posted by zcrself View Post
    Sometimes, when my program runs, there is a error "segmentation error", but I don't know why and where is the error. I want to handle this error, but I don't know how to do handling.

    Do you understand my meaning?
    You can run your program in a debugger like "gdb". When the debugger encounters segfault, it will tell you what line of code the problem is.
    If you don't want to do that. Try to predict what parts of your program may cause that problem, and use printf to print out a statement before and after these sections are executed.

    It's just better to use the debugger.
    Last edited by nimitzhunter; 12-23-2010 at 10:28 PM.
    "All that we see or seem
    Is but a dream within a dream." - Poe

  15. #15
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    Quote Originally Posted by nimitzhunter View Post
    You can run your program in a debugger like "gdb". When the debugger encounters segfault, it will tell you what line of code the problem is.
    If you don't want to do that. Try to predict what parts of your program may cause that problem, and use printf to print out a statement before and after these sections are executed.

    It's just better to use the debugger.
    java language has try-catch function,
    what does C language has?

    Can "try-catch" function handle the error "segmentation fault"

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to write a C code that evaluates 7, 7, 7, 1 = 100
    By filanfistan in forum C Programming
    Replies: 8
    Last Post: 10-21-2005, 07:37 AM
  2. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 12:55 PM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. Some humour...
    By Stan100 in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 11-06-2003, 09:25 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21