Thread: De-allocation of a matrix.

  1. #16
    Registered User
    Join Date
    Jun 2013
    Posts
    66
    Well, yeah, it is your problem; you've kind of made it a point to make it your problem by saying the problem is questionable or even imaginary.
    I'm not the one who attempted to correct code that was correct in the first place. Nor am I the one who linked to a FAQ that says "use whichever you like provided you are aware of the issues" as evidence that my valid code was wrong. Just sayin'.

    Just because you've never seen tools that misses an improper cast from `malloc' doesn't mean that such don't exist and aren't unfortunately prolific.
    I included compiler warnings and lint as a catch all for if the type of the pointer changes and the programmer is dumb enough to not check for type casts (those can be in other places than in front of malloc, by the way). But as far as the malloc and stdlib.h pairing goes, one does not need any tools other than a functioning brain to make sure stdlib.h is included.

    You seem to have a very poor opinion of every programmer on the planet if you think they are too stupid to include stdlib.h either before or after typing "malloc".

    Outside of your perfect little world, casting malloc in C causes more harm than good.
    [citation needed]

  2. #17
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    It's also possible to create a dynamic matrix with a single call to malloc():

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define NROW 10
    #define NCOL 10
    
    int main(int argc, char *argv[])
    {
        int **matrix = (int**)malloc((NROW * sizeof(*matrix)) + (NCOL * NROW * sizeof(**matrix)));
        size_t i, j;
    
        for (j = 0; j < NROW; j++){
            matrix[j] = (int*)(&matrix[NROW])+(j*NCOL);
        }
    
        for (j = 0; j < NROW; j++){
            for (i = 0; i < NCOL; i++){
                matrix[j][i] = (int)(j*0x10 + i);
            }
        }
    
        for (j = 0; j < NROW; j++){
            for (i = 0; i < NCOL; i++){
                printf("%02x ", matrix[j][i]);
            }
            printf("\n");
        }
    
        free(matrix);
    
        return(0);
    }

  3. #18
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    and the programmer is dumb enough to not check for type casts
    O_o

    (those can be in other places than in front of malloc, by the way)
    o_O

    Indeed. I feel certain this is part of the point Salem has made.

    There is no way to search for "(unknown *)malloc" without having very good tools, but if you have good tools, your compiler is going to catch a bad cast.

    In other words, by not putting casts where they are never necessary you don't need to check for casts.

    You like pushing the line, let me show you how: is the programmer dumb enough to use casts where they aren't necessary? ^_^v

    You seem to have a very poor opinion of every programmer on the planet if you think they are too stupid to include stdlib.h either before or after typing "malloc".
    Indeed.

    I wouldn't trust the lot of you with a BASIC interpreter.

    That is though, entirely besides the point Salem made: we deal almost exclusively with newbies on this forum.

    You'd be silly to think a newbie, regardless of brainyness, is going to know to include "stdlib.h" for `malloc' or always remember to add the header.

    Of course, a good compiler will complain about the `int' conversion from the implicit declaration...

    Oh, wait, no, as we are all aware, the explicit cast will silence a lot of compilers.

    Soma

  4. #19
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by rcgldr View Post
    It's also possible to create a dynamic matrix with a single call to malloc():
    I may be wrong, but I think this may suffer alignment problems. Imagine you are creating a 2-d array of some 8-byte type (which requires 8-byte alignment), on a system with 32-bit pointers (e.g. uint64_t on a x86 arch). malloc will return an address that has the largest alignment restrictions required by the implementation. Let's assume that it's 8 bytes (though the size is irrelevant).

    Now, after the malloc call, matrix points to some address, say 0x08102008. If you have 3 rows, you will use the following three 4-byte pieces of memory to store the row pointers:
    0x08102008 (through ...0B)
    0x0810200C (through ...0F)
    0x08102010 (through ...03)
    Making &matrix[nrow] = 0x08102014, which is where you start your 2-d array addressing, meaning matrix[0][0] has the address 0x08102014. That's a 4-byte alignment for a type requiring 8-byte alignment.

    Again, I could be wrong, but I think this is a valid concern.

  5. #20
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Huh... This answers my question, "Are there trolls even on the C programming board?" And the answer is "Yes, yes there are."

    So, from what I've gathered, this whole argument that seems to have blown up in like a day stems from type-casting a malloc return in C. I hate that in C++ I have to type-cast my malloc returns because Lord knows I can't be bothered to use new(). I don't believe in it, I think it's magic and I don't understand it so it scares me. I re-name all my classes to structs just so I can sleep better at night. If anything, I'd rather just write my own new() procedure myself but looking at the source code, it seems kind of hard. I'd rather just assign function pointers myself but at that stage, there's little point in even using objects anyway because I'm not saving any steps.

    And back to the argument, I'm guessing sonjared is arguing that it's perfectly fine C-style to type-cast your malloc returns.

    The answer to this argument is, does the code work? Does the code do what needs to be done?

    That is the purpose of programming. Everything else is just semantics and I'm sorry, that's a fact. If you're literally getting the same job done, then the code is 'successful'.

    However, I do agree that there is a such thing as technique and there is good and bad technique and even though two different programs can do the same thing, it is possible for one to do it better.

    sonja, the only reason people on this board jumped on you is because most of them seem to be authors or professionals or in academia and phantom is right, there's a lot of newbies here, myself included. Now, it's very, very important that when newbs come here, they receive proper information. They need to be shown how to do things the best and oftentimes, the best is entirely language-specific. Claiming that your code is both C and C++ compatible is a weak argument. While it may be valid in C to do, it doesn't need to be done and as well know, good code is entirely what needs to be done and nothing more. Type-casting when not necessary is a sign of poor programming by that principle. It's the equivalent to, I can just walk into the living room and I can walk around the house first then do it.

    Your first post was good, sonja, about matching malloc's and free's because I wouldn't have explained it any differently myself. I don't know enough CS to be able to manipulate memory addresses or that link std posted which looks like pointer magic to me, Imo. And that seems to be what the OP was asking about was this, 2D dynamic array in continuous memory locations (C) | G. Samaras

    And I do like that sonja noticed phantom's attitude. I'm also glad phantom admitted he was arrogant because I think he is but at the same time, I think he's incredibly intelligent and will more often than not, having something insightful, intelligent and useful to say. Believe me, I had a similar initial reaction until I realized he was one of those CS majors in school which is great because I love the grumpy cat computer scientists. I think they're fun to bug because they like to act like they don't have emotions but they're giant softies.

  6. #21
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    I hate that in C++ I have to type-cast my malloc returns because Lord knows I can't be bothered to use new(). I don't believe in it, I think it's magic and I don't understand it so it scares me. I re-name all my classes to structs just so I can sleep better at night. If anything, I'd rather just write my own new() procedure myself but looking at the source code, it seems kind of hard.
    O_o

    Newbie C++ programmers like you are what make baby Cthulhu cry.

    At your next, earliest convenience and preferably in this order:

    Code:
    Accelerated C++
    The C++ Standard Library
    Effective C++
    More Effective C++
    Effective STL
    Exceptional C++
    More Exceptional C++
    Exceptional C++ Style
    C++ Templates
    C++ Template Meta-programming
    I think they're fun to bug because they like to act like they don't have emotions but they're giant softies.
    I don't think I've ever been accused as being anything other than a softy.

    (Well, "idiot" and "fugly", but I don't think that's relevant.)

    Certainly, I've never been accused of being "macho", "manly", or "emotionally rigid".

    Soma

  7. #22
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by rcgldr View Post
    It's also possible to create a dynamic matrix with a single call to malloc():
    Quote Originally Posted by anduril462 View Post
    I may be wrong, but I think this may suffer alignment problems. Imagine you are creating a 2-d array of some 8-byte type (which requires 8-byte alignment), on a system with 32-bit pointers (e.g. uint64_t on a x86 arch) ... odd number of rows.
    It's possible. One example of this would involve 4 byte pointers, and 8 byte doubles. I'm not sure if an 8 byte double would need to be on an 8 byte boundary (or if it might be faster depending on cache implementation) in a 32 bit environment. In this case it would be better to use two calls to malloc(). You could modify the code with the single call to malloc() to allocate extra space (like an even number of rows even if not used) and/or round the address upwards for the first instance of data, but that would be awkward.

    The point of posting that example was to show yet another possible alternative for a dynamic matrix in response to the original post.
    Last edited by rcgldr; 06-28-2013 at 07:25 PM.

  8. #23
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MutantJohn
    And back to the argument, I'm guessing sonjared is arguing that it's perfectly fine C-style to type-cast your malloc returns.

    The answer to this argument is, does the code work? Does the code do what needs to be done?
    With respect to correctness those are the right questions to ask. With respect to style, that is not so, since style is concerned with things like readability, consistency and avoidance of possible pitfalls under maintenance.

    Quote Originally Posted by MutantJohn
    That is the purpose of programming. Everything else is just semantics and I'm sorry, that's a fact. If you're literally getting the same job done, then the code is 'successful'.
    "First, we want to establish the idea that a computer language is not just a way of getting a computer to perform operations but rather that it is a novel formal medium for expressing ideas about methodology. Thus, programs must be written for people to read, and only incidentally for machines to execute."
    - Abelson and Sussman, Structure and Interpretation of Computer Programs

    Abelson and Sussman's statement about programs being written "only incidentally for machines to execute" is something of an exaggeration, especially when there is some business related deadline to meet. On the other hand, there is a philosophy here about writing good programs: programs that are not just correct now, but will continue to remain correct under maintenance because they are meant for the maintainers to read. Hence, style (beyond mere formatting rules) is important.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #24
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by MutantJohn View Post
    Your first post was good, sonja, about matching malloc's and free's because I wouldn't have explained it any differently myself. I don't know enough CS to be able to manipulate memory addresses or that link std posted which looks like pointer magic to me, Imo. And that seems to be what the OP was asking about was this, 2D dynamic array in continuous memory locations (C) | G. Samaras
    Exactly
    This is the answer to the question in the first post. I think this thread is done
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  10. #25
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I like you, laserlight

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Finding a sub-matrix in a bigger matrix
    By pashakhanloo in forum C++ Programming
    Replies: 1
    Last Post: 10-31-2012, 10:42 AM
  2. reading a matrix and printing out the matrix
    By Lina_inverse in forum C Programming
    Replies: 9
    Last Post: 10-23-2012, 04:09 PM
  3. Replies: 6
    Last Post: 05-14-2011, 09:28 AM
  4. Need help in Matrix Addition & finding Inverse of a Matrix
    By ssatyan.129 in forum C Programming
    Replies: 6
    Last Post: 05-15-2009, 02:48 PM
  5. Matrix: Reloaded + Enter The Matrix (the game)
    By LuckY in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 04-18-2003, 12:35 AM