Reputation: 439
This is program in book “The c programming language”.
There is an error:conflicting types for 'strdup'! When encounter function 'strdup'.But if you change 'strdup' to other name, for example 'strdu', the error will disappear.
I don't know WHY? By the way, I use code::blocks as my IDE.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORD 100
struct tnode {
char *word;
int count;
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree(struct tnode *, char *);
struct tnode *talloc(void);
void treeprint(struct tnode *);
int getword(char *, int);
char *strdup(char *);
/* word frequency count */
int main()
{
struct tnode *root;
char word[MAXWORD];
root = NULL;
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
root = addtree(root, word);
treeprint(root);
return 0;
}
/* addtree: add a node with w, at or below p */
struct tnode *addtree(struct tnode *p, char *w)
{
int cond;
if (p == NULL) { /* a new word has arrived */
p = talloc(); /* make a new node */
p->word = strdup(w);
p->count = 1;
p->left = p->right = NULL;
} else if ((cond = strcmp(w, p->word)) == 0)
p->count++; /* repeated word */
else if (cond < 0) /* less than into left subtree */
p->left = addtree(p->left, w);
else /* greater than into right subtree */
p->right = addtree(p->right, w);
return p;
};
/* treeprint: in-order print of tree p */
void treeprint(struct tnode *p)
{
if (p != NULL) {
treeprint(p->left);
printf("%4d %s\n", p->count, p->word);
treeprint(p->right);
}
}
/* talloc: make a tnode */
struct tnode *talloc(void)
{
return (struct tnode *) malloc(sizeof(struct tnode));
};
char *strdup(char *s) /* make a duplicate of s */
{
char *p;
p = (char *) malloc(sizeof(strlen(s)) + 1);
if (p != NULL)
strcmp(p, s);
return p;
}
.... some other function ....
Upvotes: 2
Views: 2299
Reputation: 399949
You cannot have a function of your own whose name starts with str
. That whole "namespace" is reserved, in C.
In this case, strdup()
is a standard function from <string.h>
, which your function declaration collides with.
Note that it's not enough to stop using <string.h>
, the name is still reserved so you cannot validly use it.
A couple of further notes:
const
pointer.malloc()
in C.strdup()
workalike is horribly broken, it calls strcmp()
when it means strcpy()
.sizeof(strlen(s))
is totally wrong and will cause massive problems even if you fix the strcmp()
/strcpy()
problem.A reasonable strdup()
implementation is:
char * my_strdup(const char *s)
{
char *r = NULL;
if(s != NULL)
{
const size_t size = strlen(s) + 1;
if((r = malloc(size)) != NULL)
memcpy(r, s, size);
}
return r;
}
I use memcpy()
since I know the length, it can be quicker.
Upvotes: 7
Reputation: 550
strdup is allready defined in string.h. Just rename your function.
Upvotes: 2