Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
H

HS_C_Student

@HS_C_Student
About
Posts
17
Topics
5
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Traceability of Dynamic Memory Allocation Faults
    H HS_C_Student

    My problem is that as I write larger and more complicated (C) programs, errors in manual memory management become much harder to find and more catastrophic, particularly if caused by memory corruption. I'd like to detect any DMA related errors as quickly as possible perhaps only when a debug flag is #defined. I pass a pointer to a pointer to the create and destroy object functions. Create will fail if a pointer to non NULL memory is passed which prevents doubly allocating. I am thinking of storing pointers to all allocated objects in a balanced BST, which would enable me to tell if a pointer is valid before free()in it. After Free() I can write NULL to prevent it's use and to prepare it for allocation again. Any function that wants to check if an object pointer is valid can then call a check of the BST inventory. Further I was thinking of tagging each entry with a scope of some sort so that I can check for missed Free() as soon as the object is no longer used: StartScope(foobar) CreateObj(data) Do work;;; FreeObj(data) EndScope(foobar) That way I can check at EndScope that all foobar scoped objects were freed. This would enable me to make objects that were dynamically allocated have a stack based/automatic scope for example, if they are not going to be used after the function exits. If using scopes for 'automatic' object allocation and nesting them in a stack, an error can be detected if a higher level scope is ended before a lower one. These mechanisms are all intended to trigger errors as quickly as a problem can be detected and before it worsens. And furthermore to do so with the most minimal burden on the user. I couldn't find a standard practice because garbage collection does not seem to be the same concept as detecting errors in memory management. Is this good? Is there a better way of doing it / standard practice?

    C / C++ / MFC help database data-structures debugging performance

  • How to print all source code what was running?
    H HS_C_Student

    It's hard to understand your question. I think there are many better ways of solving the problem which might include restructuring the program, especially to make that section into smaller modules or to create your own debugging interface and pass parameters through it so you have a functional means of tracking program states. If you could tighten up input validation and narrow the scope of acceptable input it may help detect bugs. The way you want to do it printing code is not even remotely a standard functionality or common practice so it is a very oversized foot you are trying to shoehorn into a small shoe and the result will likely be as comfortable. If you want to pursue it anyway it's hard to imagine without knowing your code. You could set up a custom table of watch variables and or expressions and use the stringizing operator in a macro, similar to an assert() style. #define record_str (a) (fprintf(debug, "%s : %s", #a, a)) #define record_int(a) (fprintf(debug, "%s : %s", #a, itoa(a))) Combine it with __LINE__ and or FILE or TIME C/C++ line number - Stack Overflow[^] Hope this helps

    C / C++ / MFC tutorial question

  • Choosing my next Programming Language
    H HS_C_Student

    I started programming in high school in C about 15 years ago as a hobby and did not follow programming as my career path but it has served as a useful tool periodically since then. I was more or less told that C would be a good entry language, that it would be a good foundation if I decided to learn others. That Java is bloated and grossly resource inefficient, as well as sacrificing quite a lot to be fully cross platform. That C++'s OOP leads to less resource efficient programming and that classes were a crutch to help structure code in lieu of skillfully choosing one's own good designs. But that they would make it easier to work with others by giving greater standardization to interfaces. Today I observe as follows: C was designed for specific purposes and to specific ideals, and I mostly align with them. It's small, clean, and efficient. You're free to shoot yourself in the foot, all 12 toes. Proper design practices are your responsibility (or willful irresponsibility). If you want something you can build it or borrow/get it from someone else. It's not large. On the other hand, pure speed and efficiency is not critical in all applications. If you are doing desktop development with a moderate amount of data, and let's say not computationally intensive graphics, the efficiency may be unnecessary. Rapid development is more critical to me now. The very minimal provisioning of the standard library slows development time, like a mostly empty toolbox. Not only mostly empty, but the tools of the standard library are very traditional and sometimes crude for what you might need. Other languages provide a much greater toolset of readily usable and easily importable features. C is not entirely outmoded but its popularity is marginal, and with that marginalization a lot of the contributions made to programming as a whole are largely unavailable. Its use is declining further with the rise of C#. Projects | The State of the Octoverse[^] I think the logical choice would be to learn C++ next.

    C / C++ / MFC csharp c++ java html css

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    Great response! Thanks!

    C / C++ / MFC code-review database data-structures architecture tutorial

  • Are there programmers that are currently using machine code and Assembly?
    H HS_C_Student

    Almost forgot one entire category: Reverse Engineering.

    C / C++ / MFC question

  • Are there programmers that are currently using machine code and Assembly?
    H HS_C_Student

    I'll take a guess!

    Quote:

    Are there programmers that are currently using machine code and Assembly?

    YES.

    Quote:

    If yes, why?

    Maybe you want to work in computer security?

    Quote:

    So You Want To Be A Malware Analyst - Malwarebytes Labs | Malwarebytes Labs[^] In order for a Malware Analyst to be able to read the malware code, they will need to disassemble it. Unfortunately, the highest language derived from binary code is Assembly, which is the last level of human readable code. Therefore, it is imperative that a would-be Malware Analyst, also learn how to read and write Assembly code.

    Maybe you want your code to be very efficient (very large program, or very minimal computing resources?). http://www.agner.org/optimize/optimizing\_assembly.pdf See the 10 or so reasons found here:

    Quote:

    1.1 Reasons for using assembly code Assembly coding is not used as much today as previously. However, there are still reasons for learning and using assembly code. The main reasons are:

    Or maybe you are working in an embedded environment... [Digital Logic design, Assembly Language & Embedded Systems development]

    Quote:

    If yes, are there many programmers that are currently using machine code and Assembly? If yes, why?

    To each his own?

    C / C++ / MFC question

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    It seems like in this signed/unsigned case typecasting allows you to change the way the variable is evaluated in expressions. I think that is typical of typecasting in general, it changes interpretation. On the other hand I think if you typecast to a data type with a different size it does not just affect the expression but also the raw value. Please see my newest reply to the main topic. Thanks

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    It seems like in this signed/unsigned case typecasting allows you to change the way the variable is evaluated in expressions. I think that is typical of typecasting in general, it changes interpretation. On the other hand I think if you typecast to a data type with a different size it does not just affect the expression but also the raw value. Please see my newest reply to the main topic. Thanks

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    I wrote a small demonstration of the issue. Peter and Paul are writing ticketing system software and Peter makes a mistake swapping two variables and creating a negative number which is passed as an unsigned integer to Paul. Paul makes a mistake thinking an unsigned int will not cause an out of (lower) bounds array access if it passes the test "index >= 0". Peter makes a mistake, Paul fails to catch it, the memory is potentially corrupted and undefined behavior results. That's the PRINCIPLE the code is meant to demonstrate, which is the only purpose of this code. As an alternative I put in a boundary check based on the address the index would have us access and the addresses of the first and last members of the array. I think that's a better approach. It should match the way the array is accessed exactly and it should be completely independent of variable size, type, typecasting, and bitwise representation. As an aside, VS on the maximum warning level does not warn for the ints passed to the function that was declared with unsigned ints. Also, the compiler can't foresee that a negative value will be passed to the function because the sign of that variable is determined at run time.

    #include
    #include
    #include

    //Paul writes this code
    int get_available_seat_count(unsigned int *seating_counts, unsigned int row_index, unsigned int num_rows, unsigned int seats_per_row)
    {
    if(row_index < 0)
    {
    printf("row_index < 0: TRUE\n");
    return -1;
    }
    else
    printf("row_index < 0: FALSE\n");

    //preferable method?:
    if(&seating_counts[row_index] < &seating_counts[0])
    printf("Array minimum boundary violation, index is %d\n", row_index);

    if(&seating\_counts\[row\_index\] > &seating\_counts\[num\_rows-1\])
    	printf("Array maximum boundary violation, index is %d\\n", row\_index);
    
    return seats\_per\_row - seating\_counts\[row\_index\];
    

    }

    //Peter writes this code
    void main()
    {
    //row 0 is the back of the theater, row[num_rows-1] is at the stage
    int num_rows = 12;
    int seats_per_row = 40;
    int n_available_seats;
    int row_index;
    unsigned int seating_counts[12];
    int i;

    //set the current state of the theater:
    srand((int)time(NULL));
    for(i = 0; i < num\_rows; i++)
    	seating\_counts\[i\] = (unsigned int)rand() % seats\_per\_row;
    
    printf("Customer: are there any seats available in the third row from the stage?\\n\\n");
    row\_index = 3;
    
    //rows are stored in reverse order from customer request, subtract row\_index to get offset
    n\_available\_sea
    
    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    Before I got your reply I did a little more investigating into the issue. I was looking at the bitwise representation which I noticed is 2C as you said. I wrote this small program to test it out. Here is the output:

    //Declare an int and unsigned int, initialize to -1, check bit representation:

    //int int_neg_1 = -1;
    11111111111111111111111111111111

    //unsigned int uint_neg_1 = -1;
    11111111111111111111111111111111

    //Cast the unsigned int to int, check representation:
    (int)uint_neg_1;
    11111111111111111111111111111111

    //Compare printf as signed and unsigned int for all three:

    int_neg_1 : %d: -1, %u: 4294967295
    uint_neg_1: %d: -1, %u: 4294967295
    (int)uint_neg_1: %d: -1, %u: 4294967295

    //This is the thing that caught me off guard. "uint_neg_1 < 0" does not evaluate to true.

    int_neg_1 < 0: True
    uint_neg_1 < 0: False

    //If however, I cast the unsigned int to "int" it seems to force interpretation as a signed number:
    (int)uint_neg_1 < 0: True

    So it seems that the bitwise storage and representation for signed and unsigned integers is the same. The typecast to int changed the evaluation of the expression. I'd like to see / understand the difference in the assembly instructions because I think that is probably where the paths diverge.

    Quote:

    There is hence absolutely no point in testing an unsigned integer for being negative! It has no capacity of being negative!

    That's what I believed, but based on my experiment it's not safe to rely on the "unsigned" type as an indication of being >= 0. If someone invokes my function with "-1" and it is written without the bounds check, the result is an access violation. As a design practice my code should catch the error of the caller. I have a bad headache, I apologize if I've made mistakes. See this post for the use case of an unsigned int < 0 check: Re: (C) Robust code Should an unsigned int array index be tested for "< 0" - C / C++ / MFC Discussion Boards[^]

    /* code sample for demonstration and testing purposes */

    #include #define print_binary(a) \
    for(j = 31; j >= 0; j--) \
    printf("%c", a & (1 << j) ? '1' : '0'); \
    printf("\n\n");

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    leon de boer wrote:

    What you are ignoring is the code is invalid and would fail any software audit .. you handed that junk to me and I would sack you.

    I'm writing proof/test of concept code to enhance my understanding of safe and secure programming practices. Of course it's invalid, that's the actual point. You should fire the guy who tests the security of code on your customers instead :-)

    leon de boer wrote:

    What you are ignoring if you turn the compiler warning levels to max then your code won't compile .. it will give you a fatal error. At half-arse programmer wannabe settings it probably just gives you a warning about passing a signed integer into an unsigned integer interface.

    Actually I wasn't aware of how to force my IDE to use the strictest evaluation, but I know now, thanks for the tip. You may be disappointed as it notices the issue now but only generates a warning:

    Quote:

    warning C4245: 'function' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch

    leon de boer wrote:

    However in the real commercial world you run the compiler settings max and your code must not invoke any warning at all. Any good university when you submit your code for evaluation will have the compiler set to max you generate a warning you fail.

    Do they also run static code analysis? Are there any freeware tools I can use? Haven't looked into it yet.

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    Yes I know, the code sample I provided was only to explore / demonstrate the unsigned int behavior. Thanks.

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    I'm genuinely surprised and my paranoia has been rewarded. I think I've misunderstood something fundamental. Here is a code sample:

    #include

    //void print_iterator(int integer_array[], int index)
    void print_iterator(int integer_array[], unsigned int index)
    {
    unsigned int i;

    if(index < 0)
    {
    	printf("Index violation!\\n");
    	return;
    }
    else
    	printf("Passed index validation: %d, as %u\\n", index, index);
    
    for(i = 0; i < index; i++)
    {
    

    // printf("%d\t", integer_array[i]);

    	if(i == 20)
    	{
    		printf("Loop overrun, undefined behavior\\n");
    		return;
    	}
    }
    

    }

    main()
    {
    int ints[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

    print\_iterator(ints, -1);
    

    }

    If the index argument is declared as an unsigned int, it seems it will ALWAYS pass the bounds check when -1 is passed as the parameter, and produce this output:

    Quote:

    Passed index validation: -1, as 4294967295 Loop overrun, undefined behavior Press any key to continue . . .

    If it is declared as an int (uncomment the first function line, comment out the second one) it will work properly:

    Quote:

    Index violation! Press any key to continue . . .

    Anyone know why?

    C / C++ / MFC code-review database data-structures architecture tutorial

  • (C) Robust code Should an unsigned int array index be tested for "< 0"
    H HS_C_Student

    Suppose I have a function that takes an array pointer and an index declared as type unsigned int and the function will access the array at that index. AFAIK "Index < 0" should never evaluate to be true regardless of what the caller passed because the unsigned type will control how the bits at the address of Index are interpreted and there will be no interpretation of a bit as an indication of sign. So implicitly an unsigned int is not capable of an access violation Below / before an array's first element given the pointer arithmetic. All that being said it does not seem at all necessary to test it. There are other reasons to use the test however. #1 it may improve readability as someone who reads the code sees that a full boundary check is being done #2 it may make the code symmetric with other code that tests upper and lower boundaries of any other type of variable #3 if the function is later modified and the type is accidentally changed to int (for example the types are changed when porting to a different machine architecture) or the code is copy and pasted to a different context where Index is not unsigned, omitting the bounds check introduces the possibility of an access violation #4 I think it's possible, perhaps likely, that an intelligent compiler will optimize it out completely, even if it didn't we're not talking about a grave loss of efficiency. So although I feel stupid writing what seems to be redundant and unnecessary code and concern myself with conciseness, for a robust application it seems worthwhile.

    C / C++ / MFC code-review database data-structures architecture tutorial

  • Overworked and Isolated - (Lazy?) Help Requests
    H HS_C_Student

    Hello, I have a mild form of Autism that makes it Very difficult for me to communicate without being verbose, but I will try to be brief. My company has two major offices, one where we do all of our software development and one where I work. We are very far apart and run independently with very little communication. For many various (and legitimate) reasons our software has fallen extremely far behind, maybe 1-2 years past due. I learned some C programming about 15 years ago mostly on my own with the bible by (Ritchie and Kernighan?) and with some mentoring, but ended up in a completely different career. I decided to try and help fix our software and I worked very hard (20hrs a week after work). I researched and learned and developed a successful proof of concept project showing I could do the work. This I presented to the bosses and they said Great! and gave me a full time development position. I am the only one in my entire office who understands programming and software development in any detail. They gave me whatever resources they could get for me which I greatly appreciate. However, as I began developing new software from a fresh perspective and a different approach, I said let me extend our existing work with mine to bridge the gap as quickly as possible and I started looking into our internal database format / structure. They said "Our existing work is junk and we don't want to cross breed the two approaches, we will not share information about our ways with you. Please develop a proof of concept for your approach in two weeks". I said that will take four weeks. They said "We need to make a decision about the direction of our development for 2019 and we need to make it right now". And my ultimate boss said "get it done". So I work 6-7 days a week 55-60 hours again. Which is all OKAY, except that short term deadline sucks. Because of it I have to rush my code, putting off restructuring and refactoring as it grows, ignoring exception handling for thusfar unencountered scenarios and whatever other myriad shortcuts I've taken that should be corrected. The TODO list is a mile long; it's not the way I work. It affects my decision making; I do plenty of work just to try and make the deadline that will be a useless waste in the long term. It's a little hacked up and ugly but greatly improved this weekend. I also have to look at each new roadblock and try to find a temporary shortcut that is faster than a real solution. And I have to do all of this to achieve a result

    The Soapbox help database question career

  • Which type of Regex best to learn for programming with C?
    H HS_C_Student

    As far as I can tell there are at least three main types; POSIX basic, POSIX extended, and Perl Compatible. There's a list of engines here: Comparison of regular expression engines - Wikipedia[^] And apparently some differences between PERL and PCRE: Perl Compatible Regular Expressions - Wikipedia[^] I don't know/understand if let's say 80 or 97 percent of the Regex syntax is the same between one version or another or if they are distinct subtypes with significant differences. I don't know if they all support ascii, Unicode, and utf encoding, or whether they are all capable of returning matched variables or if some are only providing a match/no match result.

    ATL / WTL / STL regex json perl algorithms question

  • Which type of Regex best to learn for programming with C?
    H HS_C_Student

    I like C but I feel it's Achilles heel is string processing. I've started to do a lot of parsing of text databases in arbitrary format without documentation lately and I need to adapt. What I need to do is define patterns - expected format for the data and to store the values only if the whole string matches that known pattern. Input validation. I'd rather not run the rest of my code without verifying the input conforms. I think regular expressions are the best way to augment my existing skills without learning a new language, but regexes seem kind of varied and mixed breed. Perl (5?) Seems to have formal standardization of regexes which is supported in many searching and text editing programs. There's also PCRE which I can compile on windows or download precompiled lib/dll. Should I learn Perl regexes and use PCRE or am I overlooking things?

    ATL / WTL / STL regex json perl algorithms question
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups