Question

I found this code block in The UNIX Programming Environment (published with a copyright date of 1984).

chp8->hoc3->symbol.c

char *emalloc(n)    /* check return from malloc */
unsigned n;
{
char *p, *malloc();

p = malloc(n);
if (p == 0)
    execerror("out of memory", (char *) 0);
return p;
}

What's the meaning of:

char *p, *malloc();

It's really strange?

Was it helpful?

Solution

 char *p, *malloc();

is declaring a pointer to char named p and a function named malloc (In these K&R C days, void* did not exist).

This is old Kernigan & Ritchie C (from the 1980s). The C standard has evolved significantly since that time. Current C standard is C11, and its previous version C99 is very widely used.

Don't code this way today. malloc is defined in <stdlib.h> and it might be some inlined function there (but usually is not).

Your function is often conventionally called xmalloc today; you'll need to add

#include <stdlib.h>
#include <stdio.h>

in the start of your file (since malloc and exitis declared in <stdlib.h> and EXIT_FAILURE is defined there, and perror is declared in <stdio.h>), and would have been defined as

 void* xmalloc(size_t sz) {
    void* p = malloc(sz);
    if (!p) {
       perror("malloc");
       exit(EXIT_FAILURE);
    };
    return p;
 }

and declared in some header of yours with

 void* xmalloc(size_t sz);

I suggest reading a newer book. On Linux, consider at least the Advanced Linux Programming book (which is dated from 2001).

If using GCC you could add function attributes to your function declaration.

OTHER TIPS

Most of the confusion comes from using an old book, which uses a very old version of C (called K&R C). I'll list them

1. Standard functions declared unnecessarily

char *p, *malloc();

can be broken into

char *p;
char *malloc();

The latter declares a function named malloc which returns a char*, there's no information on the type of arguments it takes. In modern C (C11 or C99 or even C89), you'd do

#include <stdlib.h>

and start using malloc without worrying about its declaration, which would be void* malloc(size_t size); which comes from the included header.

2. Function declaration and definitions used are archaic

Say you've a function to add two integers, according to the old book you've, it'd declare it as int add(); (or perhaps not declare it at all, since the default type is taken as int when undeclared) and define it as

 int add(x, y)
    int x;
    int y;
 {
    return x + y;
 }

While in modern C, you'd do declare it as int add(int, int); and define it as

 int add(int x, int y)
 {
     return x + y;
 }

These were standardized and called the ANSI C, ISO C or C89 (informally). K&R's C book has 2 editions, the older edition suffers from the same issues your book has; hence it's recommended to use the 2nd edition which was written on ANSI C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top