Thread: Exceptions in C

  1. #1
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184

    Exceptions in C

    Exists try catch or similliar for C ?

    I have a big problem with strings, and I need continue executing the program before a exception in string conversion, or memory allocation.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Not in standard C, there isn't.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    in this case, how the best method to get a memory error, or string error ?

    only with function returns ?

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    What sort of error?

    A "replacement" for try/catch can be made by having (a stack of) longjmp buffer(s), and using setjmp to define the "catch" point, and longjmp to return to the setjmp'd location. However, there's a lot of things to take into account: longjmp doesn't do any clean-up. C++ has the ability to clean up any objects created between the exception and teh catch.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    ok,

    in this moment Im have a big problem with memory limit,
    i will study more this

    thank's

  6. #6
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by matsp View Post
    What sort of error?

    A "replacement" for try/catch can be made by having (a stack of) longjmp buffer(s), and using setjmp to define the "catch" point, and longjmp to return to the setjmp'd location. However, there's a lot of things to take into account: longjmp doesn't do any clean-up. C++ has the ability to clean up any objects created between the exception and teh catch.

    --
    Mats
    In addition, longjmp() can destroy the contents of local variables because of compiler optimizations (if a variable is held in a register, then upon a longjmp this variable will be erroneously "restored" to some previous value even though it has been updated in the interim between setjmp() and longjmp() ). On the whole it's not reliable at all.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677

    Unhappy

    So, assuming you can catch that you've run out of memory, what are you going to do about it?

    Are you genuinely running out of memory, or is it caused by a leak of some sort?

    If the latter, perhaps you want to track where you allocate and free, and what memory you have allocated and freed.

    There are ways to "track" your memory allocations. For example:
    Code:
    // trackmalloc.h
    #ifndef INTERNAL
    #define malloc(x) trackmalloc(x, __LINE__, __FILE__)
    #define free(x) trackfree(x, __LINE__, __FILE__)
    #endif
    void *trackmalloc(size_t size, int line, const char *file);
    void trackfree(void *ptr, int line, const char *file);
    Then implement the trackmalloc() and trackfree() functions:
    Code:
    #define INTERNAL
    #include "trackmalloc.h"
    #include <stdlib.h>
    
    struct memblock
    {
       long magic;
       struct memblock *next;
       struct memblock *prev;
       const char *file;
       size_t size;
       int line;
    };
    
    #define MAGIC 0x12345678
    #define MAGIC 0x87654321
    // Note: Above may need padding on 64-bit machines. Should be OK on 32 and 16-bit machines. 
    struct memblock *memblock_list = NULL;
    
    void *trackmalloc(size_t size, int line, const char *file)
    {
        struct memblock *mb = malloc(size + sizeof(*mb));
        if (!mb)
            // May want to output some error message here!
           return NULL;
        mb->magic = MAGIC1;
        mb->file = file;
        mb->line = line;
        if (memblock_list) mb->prev = memblock_list;
        mb->next = memblock_list;
        memblock_list = mb;
        return (void *)&mb[1];  
    }
    
    void *trackfree(void *ptr, int line, const char *file)
    {
        if (!ptr)
           return;
        else
        {
            struct memblock *mb = ((struct memblock *)(ptr))[-1];
            if (mb->magic != MAGIC1)
            { 
                // Bad free. 
            }
            mb->magic = MAGIC2;
            if (mb ==  memblock_list)
            {
                memblock_list = mb->next;
            }
            // Unlink it. 
            if (mb->next)
               mb->next->prev = mb->prev;
            if (mb->prev)
               mb->prev = mb->prev->next;      
            free(mb);
        }
    }
    I should mention I just typed that in - it may have compile and runtime errors in it.

    --
    Mats
    Last edited by matsp; 01-05-2009 at 01:45 PM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by sergioms View Post
    Exists try catch or similliar for C ?

    I have a big problem with strings, and I need continue executing the program before a exception in string conversion, or memory allocation.
    Well, memory allocation with malloc can be "handled" because malloc returns NULL on error. As for memory conversion, that depends on the function. For example a function might return lets say 0 when you convert an invalid sting to an int. Or something else.
    In any case, try/catch is not the only way to handle "exceptions". You can just use the return value of functions to do your job.

    Also, if you google there are try/catch methods for C that you can use, but of course the code won't be portable this way.

    You can post your code and get suggestions on how to handle errors in C

  9. #9
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    i know exeptions from JAVA
    there is OUT OF BOUND EXEPTION when you read a cell in an array which index is bigger then the size.
    you handle the exception by saying
    Code:
    try
    {
    }
    catch{
    }
    which is basicly tells you what to do in case of the exception
    but its java

  10. #10
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    thanks a lot for all

    matsp, for you principally.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by transgalactic2 View Post
    i know exeptions from JAVA
    there is OUT OF BOUND EXEPTION when you read a cell in an array which index is bigger then the size.
    you handle the exception by saying
    Code:
    try
    {
    }
    catch{
    }
    which is basicly tells you what to do in case of the exception
    but its java
    But that's hardly meaningful in a language that doesn't do try/catch, is it?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    Im using a ICP-i7188EX

    http://www.icpdas.com/products/PAC/i.../7188E_PAC.htm

    512 K SRAM

  13. #13
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    And lets don't forget that in order to handle an exception an expression has to throw it. If you don't do bound checking you won't handle an exception no matter the language.

    EDIT: You can use functions and create an elegant way of handling simple exceptions in C. You can use goto/break to leave a big chunk of code like try/catch. For example:
    Code:
    void* ptr safe_malloc(void** ptr, int times)
    {
        *ptr = malloc(times * sizeof(**ptr));
        if (*ptr == NULL) {mem_flag = 0; return 1;}
        return 0;
    }
    
    
    ....
    while(1){       //TRY
       if (safe_malloc(&arr1, 123)) break;
       ...
       if (safe_malloc(&arr2, 123)) break;
       ...
       break;
    }
    if (!mem_flag)        //CATCH Memory exception
    {
        ...
    }
    if (!out_of_bounds_flag)      //CATCH Out of bounds exception
    {
        ...
    }           
    if (1)                          // FINALLY
    {                          
        ...
    }
    Last edited by C_ntua; 01-05-2009 at 02:12 PM.

  14. #14
    Registered User
    Join Date
    Dec 2008
    Posts
    104
    you could always use window's GetLastError() function, but of course, that would make it strictly OS-dependant.

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by abraham2119 View Post
    you could always use window's GetLastError() function, but of course, that would make it strictly OS-dependant.
    And not available in the DOS-like OS that the microcontroller in this case has.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Are Exceptions effective?
    By Petike in forum C++ Programming
    Replies: 5
    Last Post: 09-13-2008, 12:23 AM
  2. Intercepting Fortran exceptions
    By MarkZWEERS in forum C++ Programming
    Replies: 2
    Last Post: 08-06-2008, 09:13 AM
  3. Debug --> Exceptions in Visual Studio 2005
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 08-10-2007, 02:12 AM
  4. Need advice: catch exceptions or call methods to check bits?
    By registering in forum C++ Programming
    Replies: 1
    Last Post: 10-03-2003, 01:49 PM
  5. Throwing exceptions with constructors
    By nickname_changed in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2003, 09:21 AM