I am currently reading/learning c. I often like to look at code while I read, - to see more practical use then often are feasible in educational books.
I am looking at some code from wget.
Code extracted from wget.
My question goes to what is happening around the call on windows_main from within main, file main.c.
As i understand it it goes something like this:
main:
windows_main:
... this is mighty probable confusing to read... :/
Code for xstrdup:
I am looking at some code from wget.
Code extracted from wget.
Code:
/* file: mswindows.c */ void windows_main (char **exec_name) { char *p; /* Remove .EXE from filename if it has one. */ *exec_name = xstrdup (*exec_name); p = strrchr (*exec_name, '.'); if (p) *p = '\0'; }
Code:
/* file: main.c */ const char *exec_name; int main (int argc, char **argv) { /* Construct the name of the executable, without the directory part. */ exec_name = strrchr (argv[0], PATH_SEPARATOR); if (!exec_name) exec_name = argv[0]; else ++exec_name; #ifdef WINDOWS /* Drop extension (typically .EXE) from executable filename. */ windows_main ((char **) &exec_name); #endif ...
As i understand it it goes something like this:
main:
- An unchangeable pointer of type char is made by const char *exec_name
- ((char **) &exec_name) - this confuses me. Is it making a new char array with address pointing to address of pointer exec_name, or is it some sort of cast?
- What about the fact that exec_name is a const? Wouldn't this prohibit change of exec_name?
windows_main:
- windows_main takes a char array as argument.
- since exec_name is a const, a editable copy is made by xstrdup, but can this point to same location as the const?
- the pointer p is given the address of last dot ('.') in exec_name by strrchr
- if p has index higher then 0, the value at that index is given '\0', thus terminating the string exec_name at that position.
... this is mighty probable confusing to read... :/
Code for xstrdup:
Code:
void xalloc_die (void) { error (exit_failure, 0, "%s", _("memory exhausted")); /* The `noreturn' cannot be given to error, since it may return if its first argument is 0. To help compilers understand the xalloc_die does not return, call abort. Also, the abort is a safety feature if exit_failure is 0 (which shouldn't happen). */ abort (); } /* Allocate N bytes of memory dynamically, with error checking. */ void * xmalloc (size_t n) { void *p = malloc (n); if (!p && n != 0) xalloc_die (); return p; } /* Clone an object P of size S, with error checking. There's no need for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any need for an arithmetic overflow check. */ void * xmemdup (void const *p, size_t s) { return memcpy (xmalloc (s), p, s); } /* Clone STRING. */ char * xstrdup (char const *string) { return xmemdup (string, strlen (string) + 1); }
Comment