You Are Here Home > C Programming

C Programming

How Not To Write Code

I’m working on a website and it’s absolutely awful, almost all the design choices are bad so I will compile a list here as I encounter them:

1 – Don’t have fields in your database like “extra1″, “extra2″ or “extra3″ you probably need to refactor and rethink your design…

2 – Don’t have a global object and access and manipulate it from deep inside your code, here for example there is a $tpl variable which – wrongly – is called $class_tpl and it’s global, the authors are calling a pager function to create an array for rendering a pager and after they call they manipulate the $class_tpl a bit by adding paging data to it and you would think that was it, but guess what? In their pager function they again access $class_tpl and manipulate a bit more!!!

3 – Don’t ever, ever, ever, ever query your database from within your templates, never…

4 – Don’t die or exit out of functions, return error messages…

5 – Don’t output out of function either, no “echo $blah;” in a function, they should return the text string rather than printing it…

6 – Don’t ever, ever, ever repeat yourself, if you are too lazy to write a function or rethink that portion of your code, then you suck as a programmer… To be honest, I do suck sometimes, but I try my very best :)

How Not To Write Code
Comments (0)   Filed under: C Programming,General,PHP,Web Development   Posted by: Hamid

C: Determining Size Of a Malloced C Pointer At Runtime

There is no direct/cross-platform way of doing this but you could do something cool, you could do what malloc does… (Although malloc stores more data than this)

Say you want to allocate a chunk that is 100 bytes and you want to somehow attach this size to it, so you can check the size anytime later on, what you do is this: you allocate 100 bytes + sizeof(size_t) and then store the size of this chunk which is 100 at the beginning of the chunk, then you return the address of the chunk starting right after the 100:

struct chunk_header {
    size_t size;
};
 
 void *my_malloc(size_t size)
{
    size_t header_size = sizeof(struct chunk_header);
    size_t alloc_size = header_size + size;
    void *chunk = malloc(alloc_size);
    struct chunk_header *header;
    if (!chunk)
        return NULL;
    header = (struct chunk_header *) chunk;
    header->size = alloc_size; /* Or just size, it's up to you... */
    return (char *) chunk + header_size; /* char * hack, go look it up... */
}

Later on, you can check the size like so:

size_t header_size = sizeof(struct chunk_header)
void *chunk = (char *) p - header_size;
struct chunk_header *header = (struct chunk_header *) chunk;
printf("This chunk of memory is: %d bytes...\n", (int) header->size);
C: Determining Size Of a Malloced C Pointer At Runtime
Comments (1)   Filed under: C Programming,C/C++   Posted by: Hamid
« Newer PostsOlder Posts »