There is a lot of opinion in this thread, which is okay as long as a reader knows that fact.
Generally it is bad idea to cast malloc, because it is not required and may introduce subtle bugs that are hard to find, a discussion:
FAQ > Casting malloc - Cprogramming.com
Consider the use of a debugger, ex: gdb. This will help resolve crashes by examining core files, link:
RMS's gdb Tutorial: Segmentation Fault Example
Finally, allocating heap memory (malloc does this for you in C) is not all that simple.
If you allocate x+1 bytes for a string which should never be long than x, you have to check input carefully, otherwise if the string you enter is too long by a few bytes it probably will not segfault, it will simply trash a neighboring variable. Nasty.
Except for embedded systems (ex ARM), declaring strings longer than needed is less harmful, but still requires checking EVERY input string before parking it in the variable, because this makes an entry for a possible code exploit. Shell code and SQL injection come to mind.
malloc works this way in general:
1. at the beginning of code invocation, the brk() system call allocates pages of memory, and those pages then are controlled by malloc, not directly by your program code, normally. Do not call brk() on your own if you use malloc or functions like strdup which call malloc. Calling brk() directly in code that uses malloc usually results in chaos.
So if you malloc 10 bytes and page size is 8192 bytes (example), then you still have more already allocated memory available.
2. malloc keeps track of what it allocates, pages are in a page table, variables are tracked usually with some kind of descriptor. The descriptor is often a struct that consists of a pointer to the start of the variable (what malloc returns to you), and a length in bytes.
hypothetical example base on Doug Lea's original malloc:
[address of word aligned memory][length].... [word aligned memory]
So, if you increment or decrement the pointer you have (your variable) it no longer references [address of word aligned memory]. This causes free() to get nasty with you.
- finally, some of the suggestions in this thread are just that - there is both art and science in building good code.