473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

About ocurrences problem

Hi to All,

Foollowing Your suggestion, I have written this code:

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define BUFLEN 100

struct node
{
char info[BUFLEN] ;
struct node *pun ;
} ;

typedef struct node* newlist ;

void insert_myString (newlist *test, const char *buf);
int wordCounter(char *a, char *b);

int main( void )
{
char myString1[ ] = "this is the first string and after is the
second string";
char myString2[ ] = "this is the second string";
char myString3[ ] = "this is the third string; no strings after
this string";
newlist mytest = NULL ;
char myWord[ ] = "string";
int counter = 0;
int n = 0;

insert_myString(&mytest, myString1) ;
insert_myString(&mytest, myString2) ;
insert_myString(&mytest, myString3) ;

while (mytest != NULL)
{
counter = wordCounter(mytest->info, myWord);
n = n + counter;
mytest = mytest->pun ;
}
printf("The occurrences number of word 'string' in the entire
struct is: %d\n", n);
sleep(3);
}

void insert_myString(newlist *test, const char *buf)
{
struct node *prec = *test ;

// create element
struct node *p = (newlist) malloc(sizeof(struct node)) ;

if (p == NULL) {
fprintf(stderr, "Error: memory allocation\n" ) ;
exit(-1) ;
}

strcpy(p->info, buf) ;
p->pun = NULL ; // init of last element

// the list is empty
if (prec == NULL)
*test = p ;
else {
while (prec->pun != NULL)
prec = prec->pun ;

prec->pun = p ;
}
}

int wordCounter(char *a, char *b)
{
int cnt = 0;
char *sptr = a;

while ( *sptr != '\0' && ( sptr = strstr( sptr, b ) ) != NULL )
{
cnt++;
sptr += strlen( b );
}
return(cnt);
}

After I have compiled the program and it's work fine.

Now, I have inserted the same solution in a my little server program
(sorry for the lenght)

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <malloc.h>

#define MYPORT 10000
#define MAXCONN 5
#define BUFLEN 100

struct node
{
char info[BUFLEN] ;
struct node *pun ;
} ;

typedef struct node* newlist ;

typedef int Boolean;

/* Prototype */
void insertList (newlist *test, const char *buf);
int occurr_counter(newlist p, const char *buf);
int word_counter(char *a, const char *b);

int main(int argc, char *argv[])
{
struct sockaddr_in myServer, Client;
int socketfd, newsocketfd, client_len, char_recv, i, n, occur;
newlist newtest = NULL ;
char c;
char myString[BUFLEN];
char myWord[20];
Boolean done = 0;
char terminator[3]={'.','.','\n'};

/* local socket descriptor */
if ((socketfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("system call socket failed");
exit(1);
}

memset ( &myServer, 0, sizeof(myServer) );

myServer.sin_family = AF_INET;
myServer.sin_addr.s_addr = htonl(INADDR_ANY);
myServer.sin_port = htons(MYPORT);

if (bind(socketfd, (struct sockaddr*) &myServer, sizeof(myServer))
== -1) {
perror("system call bind failed");
exit(2);
}

listen (socketfd, MAXCONN);

while (1) {
client_len = sizeof(Client);
if ((newsocketfd = accept(socketfd, (struct sockaddr *)&Client,
&client_len)) < 0) {
perror("Connection accept error");
exit(3);
}
printf("Connection Opened.\r\n");
send(newsocketfd, "Wellcome!\r\n", 11, 0);
send(newsocketfd, "Send to me Your strings !\r\n", 24, 0);
send(newsocketfd, "Close the last with .. !\r\n", 34, 0);

while (!done)
{
i=0;
char_recv = recv(newsocketfd, &c, 1, 0);
while (c !='\n')
{
myString[i++]=c;
char_recv = recv(newsocketfd, &c, 1, 0);
} /* End while (c !='\n') */
myString[i]='\0';

/* insert myString in the struct */
insertList(&newtest, myString) ;

/* Is the last ? */
if (i 2 && memcmp(&myString[i - 3], terminator, 2) == 0)
{
done = 1;
} /* End di if */
} /* while (!done) */

/* Query myWord */
send(newsocketfd,"Wich word will You to search?\r\n",30,0);
i=0;
char_recv = recv(newsocketfd, &c, 1, 0);
while (c !='\n')
{
myWord[i++]=c;
char_recv = recv(newsocketfd, &c, 1, 0);
} /* End while (c !='\n') */
myWord[i]='\0';

/* I search the occurrences of myWord in the entire struct */
occur = occur_counter(newtest, myWord) ;

/* Connection closed */
send(newsocketfd,"Now I close the connection\r\n",24,0);

sleep(3);

close(newsocketfd);
printf("Connection closed.\r\n");
}
}

int occur_counter(newlist p, const char *buf)
{
int n, occ;

occ = 0;
n = 0;
while (p != NULL)
{
printf("Element: %s\n",p->info);
occ = word_counter(p->info, buf);
n = n + occ;
p = p->pun ;
}
return(n) ;
}

void insertList (newlist *test, const char *buf)
{
struct node *prec = *test ;

// element creation
struct node *p = (newlist) malloc(sizeof(struct node)) ;

if (p == NULL) {
fprintf(stderr, "'allocation memory error\n" ) ;
exit(-1) ;
}

strcpy(p->info, buf) ;
p->pun = NULL ;

// the list is empty?
if (prec == NULL)
*test = p ;
else {
while (prec->pun != NULL)
prec = prec->pun ;

prec->pun = p ;
}
}

int word_counter(char *a, const char *b)
{
int cnt = 0;
char *sptr = a;

printf("%s\n", sptr);
while ( *sptr != '\0' && ( sptr = strstr( sptr, b ) ) != NULL )
{
cnt++;
sptr += strlen( b );
}

printf( "%d\n", cnt );
return(cnt);
};

I have compiled the program (used cygWin) without errors. From cygwin
I run this program and with windows telnet I send to server the same
strings of first sample.
I have tested and the server receive and store correctly the string
sended from client.

When I search the occurrences of word "string", the server return a
mistaken number for each string.

Have You an "idea" ? I hope in Your help.

Thank You and Best Regards
Gaetano

Apr 9 '07 #1
5 1518
nick048 <ni*************@moonsoft.itwrote:
Now, I have inserted the same solution in a my little server program
(sorry for the lenght)
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <malloc.h>
This is no standard C header and I don't think you need it if you
instead use

#include <stdlib.h>

#define MYPORT 10000
#define MAXCONN 5
#define BUFLEN 100
struct node
{
char info[BUFLEN] ;
struct node *pun ;
} ;
typedef struct node* newlist ;
typedef int Boolean;
/* Prototype */
void insertList (newlist *test, const char *buf);
int occurr_counter(newlist p, const char *buf);
int word_counter(char *a, const char *b);
int main(int argc, char *argv[])
Since you never use argc or argv it would make more sense to
write that as

int main( void )
{
struct sockaddr_in myServer, Client;
int socketfd, newsocketfd, client_len, char_recv, i, n, occur;
newlist newtest = NULL ;
char c;
char myString[BUFLEN];
char myWord[20];
Boolean done = 0;
char terminator[3]={'.','.','\n'};
/* local socket descriptor */
if ((socketfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("system call socket failed");
exit(1);
}
I am not going to comment on the part of the program that deals
with the network stuff since it's not topical here in clc.
memset ( &myServer, 0, sizeof(myServer) );
myServer.sin_family = AF_INET;
myServer.sin_addr.s_addr = htonl(INADDR_ANY);
myServer.sin_port = htons(MYPORT);
if (bind(socketfd, (struct sockaddr*) &myServer, sizeof(myServer))
== -1) {
perror("system call bind failed");
exit(2);
}
listen (socketfd, MAXCONN);
while (1) {
client_len = sizeof(Client);
if ((newsocketfd = accept(socketfd, (struct sockaddr *)&Client,
&client_len)) < 0) {
perror("Connection accept error");
exit(3);
}
printf("Connection Opened.\r\n");
send(newsocketfd, "Wellcome!\r\n", 11, 0);
send(newsocketfd, "Send to me Your strings !\r\n", 24, 0);
There are 27 chars to send, not just 24...
send(newsocketfd, "Close the last with .. !\r\n", 34, 0);
....but here only 26 instead of 34.
while (!done)
{
i=0;
char_recv = recv(newsocketfd, &c, 1, 0);
while (c !='\n')
{
myString[i++]=c;
char_recv = recv(newsocketfd, &c, 1, 0);
} /* End while (c !='\n') */
This loop creates a serious problem: if the user sends you a string
that is longer than BUFLEN-1 you will start writing past the end of
the myString array.

And there's another problem that is in part resonsible for for your
getting the word count wrong: you also store the \n (and maybe even
an additional carriage-return character) you receive from the other
side in the string. If the user enters e.g. "abcabc" and then presses
RETURN what you store is "abcabc\n".
myString[i]='\0';
/* insert myString in the struct */
insertList(&newtest, myString) ;
/* Is the last ? */
if (i 2 && memcmp(&myString[i - 3], terminator, 2) == 0)
{
done = 1;
} /* End di if */
} /* while (!done) */
/* Query myWord */
send(newsocketfd,"Wich word will You to search?\r\n",30,0);
There are 31 chars to be send instead of 30.
i=0;
char_recv = recv(newsocketfd, &c, 1, 0);
while (c !='\n')
{
myWord[i++]=c;
char_recv = recv(newsocketfd, &c, 1, 0);
} /* End while (c !='\n') */
myWord[i]='\0';
And here you have the same problems as above. If the user enters
just "a" and then presses RETURN myWord will be "a\n". And
leaving the \n in the string to search for is what makes the
comparison not work as expected since the \n is in the strings
you search in only once at the very end. So the search will
always return only 0 or 1 (and 1 only if the word you're look-
ing for is at the very end of the string you search).
/* I search the occurrences of myWord in the entire struct */
occur = occur_counter(newtest, myWord) ;
/* Connection closed */
send(newsocketfd,"Now I close the connection\r\n",24,0);
There are 28 chars you need to send, not only 24.
sleep(3);
close(newsocketfd);
printf("Connection closed.\r\n");
}
}
I have compiled the program (used cygWin) without errors.
But you should have gotten a few warnings or you should increase
the warning level of your compiler...
From cygwin
I run this program and with windows telnet I send to server the same
strings of first sample.
I have tested and the server receive and store correctly the string
sended from client.
Well, except that you have additional \n characters in there, but
they are sometimes hard to see (and you may have to actually look
for them;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Apr 9 '07 #2

"nick048" <ni*************@moonsoft.itwrote in message
news:11**********************@q75g2000hsh.googlegr oups.com...
After I have compiled the program and it's work fine.

Now, I have inserted the same solution in a my little server program
(sorry for the lenght)
I didnt read the rest but heres probably the solution:
buffers received from server/client code are not zero terminated. use the
return values from recv etc
Apr 9 '07 #3
On Apr 9, 12:02 pm, "nick048" <nicosia.gaet...@moonsoft.itwrote:
Hi to All,
<snip>
strcpy(p->info, buf) ;
buffer overflow again? strncpy perhaps?

Regards,
Frodo B

Apr 9 '07 #4
Frodo Baggins said:
On Apr 9, 12:02 pm, "nick048" <nicosia.gaet...@moonsoft.itwrote:
>Hi to All,

<snip>
> strcpy(p->info, buf) ;

buffer overflow again? strncpy perhaps?
Buffer overflow is bad, so avoid copying arbitrary data into a buffer
without first ensuring that it will fit.

But arbitrary data loss is bad too.

Recommending strncpy as a not-quite-drop-in replacement for strcpy is
poor advice.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 9 '07 #5
nick048 wrote:
Hi to All,

Foollowing Your suggestion, I have written this code:

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define BUFLEN 100

struct node
{
char info[BUFLEN] ;
struct node *pun ;
} ;

typedef struct node* newlist ;
One more point that hasn't been raised, typedefs like the one above are
seldom, if ever, a good idea. By all means use a typedef as an alias
for struct node, but not for a pointer to struct node.
// create element
struct node *p = (newlist) malloc(sizeof(struct node)) ;
See why the typedef is not a good idea? Ignoring the unnecessary
casting of malloc's return, the line above is just confusing, casting
with what appears to be a different type. Much better to write

struct node *p = malloc( sizeof *p );

While you are cleaning up the code, drop the spaces before the
semicolons, they are inconsistent and odd.

--
Ian Collins.
Apr 9 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
39
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am...
51
by: Noam Raphael | last post by:
Hello, I thought about a new Python feature. Please tell me what you think about it. Say you want to write a base class with some unimplemented methods, that subclasses must implement (or...
77
by: nospam | last post by:
Reasons for a 3-tier achitecture for the WEB? (NOTE: I said, WEB, NOT WINDOWS. DON'T shoot your mouth off if you don't understand the difference.) I hear only one reason and that's to switch a...
125
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from...
3
by: Jack | last post by:
On the 1st of January 1998, Bjarne Stroustrup gave an interview to the IEEE's 'Computer' magazine. Naturally, the editors thought he would be giving a retrospective view of seven years of...
81
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there...
7
by: Edward Yang | last post by:
A few days ago I started a thread "I think C# is forcing us to write more (redundant) code" and got many replies (more than what I had expected). But after reading all the replies I think my...
10
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.