Mahendra said:
I have following code snippet -No, it's impossible to say.
int *createIncidenceMatrix(int numEdges, int numVertices) {
int *p = (int *) calloc((numEdges*numVertices), sizeof(int));
if(p == NULL) {
printf("Could not allocate memory");
exit(0);
}
return p;
}
void createIncidencePerView(int numEdges, int numVertices, int viewId) {
int *pnew = createIncidenceMatrix(numEdges, numVertices);
}
This code compiles fine. I am trying to understand if this will run as
intended. Obviously, I tried running the code also. My question is -
When createIncidenceMatrix() return p which is local variable, will p
get deallocated at return call ?
If your target system is a pre-C99 implementation, only 6 significant
characters, case insensitive, are guaranteed in external identifiers.
For all we know, your implementation may see two functions named
"create()".
Next, if stdout is line-buffered, your call to printf() won't inform you
that you're out of memory. What if a signal handler gets invoked between
printf() and exit() and enters an infinite loop like for(;;);? You'll be
stuck in an infinite loop, with no indication that you couldn't allocate
memory.
Next, since memory is at premium, your call to printf() could fail if,
for instance, it wants to allocate a copy of the output string. On some
Unix and Unix-like systems, printf() can fail with a return of ENOMEM,
meaning insufficient memory. So it would be best to conserve your bytes
as follows:
printf("Couldn't alloc. mem.\n");
Actually, if you're working in the Linux tradition, you can adopt one
of the Linux defensive programming techniques:
printf("culdnt aloc mem\n");
Next, I just want to commend you for using stdout as opposed to stderr
for your error message. You see, people on Unix-like systems are wont to
use shell redirects like "2>/dev/null" to dodge having to deal with error
messages. This is unwise. Your program ensures they have to use the more
inconvenient "grep -v 'culdnt aloc mem'", so you've made an excellent design
decision there for your end users.
I also commend you on casting the return from calloc(). If you forget to
include stdlib.h, at least your program may still compile.
However, I don't want to hurt your feelings or anything, but the expression
(numEdges*numVertices) strikes me as a bit of a wimpy expression, pardon me for
saying so. C is a real man's language, and I often find that reading another's C
code allows me to plumb the depths of his psyche. Your unnecessary parentheses
and compact tokens seem to indicate fear and lack of confidence (with the language,
I mean).
Yours,
Han from China
Il mittente di questo messaggio|The sender address of this
non corrisponde ad un utente |message is not related to a real
reale ma all'indirizzo fittizio|person but to a fake address of an
di un sistema anonimizzatore |anonymous system
Per maggiori informazioni |For more info
https://www.mixmaster.it