473,837 Members | 1,561 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(cha r *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(myt est->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(s truct 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(cha r *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(ch ar *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_fa mily = AF_INET;
myServer.sin_ad dr.s_addr = htonl(INADDR_AN Y);
myServer.sin_po rt = 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("Connect ion accept error");
exit(3);
}
printf("Connect ion Opened.\r\n");
send(newsocketf d, "Wellcome!\r\n" , 11, 0);
send(newsocketf d, "Send to me Your strings !\r\n", 24, 0);
send(newsocketf d, "Close the last with .. !\r\n", 34, 0);

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

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

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

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

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

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

sleep(3);

close(newsocket fd);
printf("Connect ion closed.\r\n");
}
}

int occur_counter(n ewlist 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(s truct node)) ;

if (p == NULL) {
fprintf(stderr, "'allocatio n 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(ch ar *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 1533
nick048 <ni************ *@moonsoft.itwr ote:
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(ch ar *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_fa mily = AF_INET;
myServer.sin_ad dr.s_addr = htonl(INADDR_AN Y);
myServer.sin_po rt = 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("Connect ion accept error");
exit(3);
}
printf("Connect ion Opened.\r\n");
send(newsocketf d, "Wellcome!\r\n" , 11, 0);
send(newsocketf d, "Send to me Your strings !\r\n", 24, 0);
There are 27 chars to send, not just 24...
send(newsocketf d, "Close the last with .. !\r\n", 34, 0);
....but here only 26 instead of 34.
while (!done)
{
i=0;
char_recv = recv(newsocketf d, &c, 1, 0);
while (c !='\n')
{
myString[i++]=c;
char_recv = recv(newsocketf d, &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(&new test, myString) ;
/* Is the last ? */
if (i 2 && memcmp(&myStrin g[i - 3], terminator, 2) == 0)
{
done = 1;
} /* End di if */
} /* while (!done) */
/* Query myWord */
send(newsocketf d,"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(newsocketf d, &c, 1, 0);
while (c !='\n')
{
myWord[i++]=c;
char_recv = recv(newsocketf d, &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(n ewtest, myWord) ;
/* Connection closed */
send(newsocketf d,"Now I close the connection\r\n" ,24,0);
There are 28 chars you need to send, not only 24.
sleep(3);
close(newsocket fd);
printf("Connect ion 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.itwr ote in message
news:11******** **************@ q75g2000hsh.goo glegroups.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.itwr ote:
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.itwr ote:
>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(s truct 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
19235
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 any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
39
3192
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 sure there are many discussions on the "problems" mentioned here. But I had this thoughts without looking into any forums or anything... it is kind of feedback.
51
7040
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 maybe even just declare an interface, with no methods implemented). Right now, you don't really have a way to do it. You can leave the methods with a "pass", or raise a NotImplementedError, but even in the best solution that I know of,
77
5700
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 database from SQL Server to Oracle or DB2 or vice versa... and that's it.... And a lot of these enterprises don't need it as they already know what database they are going to use and they don't plan on switching in and out database in the first...
125
14906
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 software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
3
2003
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 object-oriented design, using the language he created. By the end of the interview, the interviewer got more than he had bargained for and, subsequently, the editor decided to suppress its contents, 'for the good of the industry' but, as with many of...
81
7372
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 be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
7
3160
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 question about local variable initialization is still not solved. And some of the replies forked into talking about out parameters. And the thread is becoming way too deep. So I open a new thread here. My question in the previous thead has turned...
10
3752
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 Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
0
9851
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9695
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10583
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10642
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10286
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7013
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4060
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3128
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.