944,108 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 2320
  • C RSS
You are currently viewing page 1 of this multi-page discussion thread
Jun 24th, 2006
0

continuous string

Expand Post »
Here is the code i have written to accept string from the user.
Can you please modify the code so as it can even count the space as well as print the whole line with the spaces instead of the first word.

Thanks a lot.
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <malloc.h>
  4. #include <conio.h>
  5. int strlength (char input[])
  6. {
  7. int count = 0;
  8. while (input[count++] != '\0');
  9. return count;
  10. }
  11.  
  12. main ( )
  13. {
  14. char* s = 0;
  15. char inputBuffer;
  16. int index = 0;
  17. printf("\nEnter the name u want to enter : ");
  18. while ((inputBuffer = getchar()) != '#') // some termintaing cond.
  19. {
  20. s = malloc(sizeof(char));
  21. s[index] = inputBuffer;
  22. }
  23.  
  24. printf("The length of this string is %d", strlength(s));
  25. printf("\n");
  26.  
  27. }
Super Moderator
Featured Poster
Reputation Points: 3241
Solved Threads: 719
Failure as a human
~s.o.s~ is offline Offline
8,873 posts
since Jun 2006
Jun 24th, 2006
0

Re: continuous string

>>Can you please modify the code so ...

No, I don't do homework for anyone.

>> s = malloc(sizeof(char));
This just allocates one character, causing a 1 byte memory leak on every loop iteration.
>> s[index] = inputBuffer;
Since the malloc allocates only one character, this line will just scribble all over memory and most likely cause your program to crash big-time.

How to fix the above problems: use realloc and pass the number of bytes to allocate
s = realloc(s,index+1);

Tip: sizeof(char) is ALWAYS 1 regardless of computer, operating system, or compiler.
Last edited by Ancient Dragon; Jun 24th, 2006 at 9:29 am.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2283
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,961 posts
since Aug 2005
Jun 24th, 2006
0

Re: continuous string

>#include <assert.h>
You haven't used this, so there's no point in including it.

>#include <malloc.h>
stdlib.h is the header you want for malloc.

>#include <conio.h>
You don't use anything from conio, so why kill your program's portability?

>main ( )
The correct definition for main is int main ( void ).

>while (input[count++] != '\0');
This will never return 0, even for an empty string. Is that what you want?

>s = malloc(sizeof(char));
This is your single biggest problem. It's a memory leak, and you don't allocate enough memory.

>s[index] = inputBuffer;
This is a guaranteed buffer overflow.

>printf("The length of this string is %d", strlength(s));
This is a guaranteed buffer overflow because you don't terminate the string with '\0'.

>}
main returns an int, even when it's implicitly defined. That means you must return a value or invoke undefined behavior.
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int strlength ( char input[] )
  5. {
  6. int count = 0;
  7.  
  8. while ( input[count] != '\0' )
  9. ++count;
  10.  
  11. return count;
  12. }
  13.  
  14. int main ( void )
  15. {
  16. char* s = 0;
  17. char inputBuffer;
  18. int index = 0;
  19.  
  20. printf ( "Enter the name u want to enter: " );
  21. fflush ( stdout );
  22.  
  23. while ( ( inputBuffer = getchar() ) != '\n' )
  24. {
  25. char *temp = realloc ( s, index + 2 );
  26.  
  27. if ( temp == 0 )
  28. {
  29. fputs ( "Memory allocation error", stderr );
  30. break;
  31. }
  32.  
  33. s[index++] = inputBuffer;
  34. }
  35.  
  36. s[index] = '\0';
  37.  
  38. puts ( s );
  39. printf ( "The length of this string is %d\n", strlength ( s ) );
  40.  
  41. return 0;
  42. }
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Jun 24th, 2006
0

Re: continuous string

Why don't you use s[256] so you don't need malloc. Use gets for string input. To calculate spaces (if I understood your task) just iterate the input string example: if (s[index++] == 0x20) numSpaces++;
Reputation Points: 251
Solved Threads: 29
Posting Whiz in Training
andor is offline Offline
274 posts
since Jun 2005
Jun 24th, 2006
0

Re: continuous string

>Why don't you use s[256] so you don't need malloc.
Why 256? That's the problem with using an array, the size is almost always completely arbitrary. This imposes an unnecessary limit on the program.

>Use gets for string input.
Any credibility you might have had with this post was destroyed when you mentioned gets without first preceding it with "NEVER USE".

>if (s[index++] == 0x20) numSpaces++;
Okay, and now your code doesn't quite work on a machine that uses EBCDIC instead of ASCII. C offers you character constants to avoid such a problem:
  1. if (s[index++] == ' ') numSpaces++;
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Jun 24th, 2006
0

Re: continuous string

>Why 256?

I thought its easier that way, no need for malloc or realoc.

>That's the problem with using an array, the size is almost always completely arbitrary. This imposes an >unnecessary limit on the program.

I know that, but after all its only a homework

>Use gets for string input.
>Any credibility you might have had with this post was destroyed when you mentioned gets without first >preceding it with "NEVER USE".

I admit never used string input from user in my life (maybe in school only) so I don't know whats the problem with gets, but if U say so I belive you. Sorry to misled the young student. Use fgets.

>if (s[index++] == 0x20) numSpaces++;
>Okay, and now your code doesn't quite work on a machine that uses EBCDIC instead of ASCII. C offers you >character constants to avoid such a problem:

  1. if (s[index++] == ' ') numSpaces++;

agree with this
Last edited by andor; Jun 24th, 2006 at 11:03 am.
Reputation Points: 251
Solved Threads: 29
Posting Whiz in Training
andor is offline Offline
274 posts
since Jun 2005
Jun 24th, 2006
0

Re: continuous string

Thanks a lot for all your help but let me get one thing straight.

Quote ...
No, I don't do homework for anyone.
Friend, neither do i approve of the person who does it. By saying that can you write a code i meant that couldsomeone help me write a code.


Quote ...
I know that, but after all its only a homework
No friend this is not a homework and i never did mention so, this is just a program i have written to improve my understanding.

Quote ...
>> s = malloc(sizeof(char));
This just allocates one character, causing a 1 byte memory leak on every loop iteration.
>> s[index] = inputBuffer;
Since the malloc allocates only one character, this line will just scribble all over memory and most likely cause your program to crash big-time.
@AncientDragon

Can you please explain the meaning of memory leak on each iterationand the scribbling on the memory. I am totally new to such memory concepts and i have run the prog and it is giving the correct output no junk value so how do we know that it is scribbling.


@Miss Narue
Quote ...
>printf("The length of this string is %d", strlength(s));
This is a guaranteed buffer overflow because you don't terminate the string with '\0'.
using printf this way causes buffer overflow ???

But i have modifed the prog a bit and its workin for strings.

  1. int main ( )
  2. {
  3. char* s = 0;
  4. char inputBuffer, prevBuffer;
  5. int index = 0;
  6. printf("\nEnter the name u want to enter : ");
  7. while ((inputBuffer = getchar()) != '#')
  8. {
  9. s = malloc(sizeof(char));
  10. s[index++] = inputBuffer;
  11. prevBuffer = inputBuffer;
  12. }
  13.  
  14. printf("The length from main (including null) is %d", index);
  15. printf("\nThe length from function (including null) is %d", strlength(s, prevBuffer));
  16. printf("\n");
  17. return 0;
  18.  
  19. }

Thanks to all and sorry if i said somthing bad.
Super Moderator
Featured Poster
Reputation Points: 3241
Solved Threads: 719
Failure as a human
~s.o.s~ is offline Offline
8,873 posts
since Jun 2006
Jun 24th, 2006
0

Re: continuous string

>I thought its easier that way, no need for malloc or realoc.
Yes, it is easier. The code is shorter, faster, and easier to debug. But if I asked a question that clearly wanted to use dynamic allocation and you told me to use an array, I'd be tempted to smack you.

>I know that, but after all its only a homework
How do you know that the homework doesn't require dynamic allocation?

>I admit never used string input from user in my life
It doesn't have to be user input, you can just as easily redirect from a file and the problems are still there.

>so I don't know whats the problem with gets
What if a line is longer than the buffer that you pass to gets?

>using printf this way causes buffer overflow ???
No, using strlength that way causes buffer overflow. In strlen, this is your loop:
  1. while ( input[count] != '\0' )
If the first character in the string is '\0' then there's not a problem, but because it's extremely difficult and unlikely for a user to actually have getchar return 0, that first character will not be '\0' unless you explicitly set it as such, which you don't. Therefore, the loop will walk all over memory that you don't own, and that's a buffer overflow.

>But i have modifed the prog a bit and its workin for strings.
Just because it works doesn't mean it's correct. Your modified program has all of the same problems we've already pointed out to you. I suggest you try to understand what's going on rather than just change code until it appears to work.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Jun 24th, 2006
0

Re: continuous string

>>meaning of memory leak
it occurs when you use one of the functions that allocate memory, such as malloc() then do not free the memory before using the pointer again. In the code you posted, pointer variable s was allocated over and over without ever freeing the memory. You should have called realloc() instead of malloc() so that the memory block would have been expanded.

>>scribbling on the memory
that means the program is writing outside the allocated memory, and it is not know where the program will write the data, could be almost anywhere. In the code you posted, the program could very easly be writing into other variable's memory address, destroying whatever value was legatimately there. Its something like giving a little kid a crayola and a color book -- watch the child scribble all over the page not paying any attention at all to the lines that define the picture. That's what your program was doing.
Last edited by Ancient Dragon; Jun 24th, 2006 at 6:21 pm.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2283
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,961 posts
since Aug 2005
Jun 25th, 2006
0

Re: continuous string

Quote originally posted by Ancient Dragon ...
>>meaning of memory leak
it occurs when you use one of the functions that allocate memory, such as malloc() then do not free the memory before using the pointer again. In the code you posted, pointer variable s was allocated over and over without ever freeing the memory. You should have called realloc() instead of malloc() so that the memory block would have been expanded.
But when we end the program the memory is automatically returned to the OS for its use and the prog in the end uses the same mem. it was about to use so why the realloc instead of malloc.

Even then i have heeded your advices and rewritten the code.
I even read the tutorials concering the disadvantages of scanf and gets and also flushed the stream buffer before takin input.

It compiles welll but jumps out during execution ie runtime error. The updated code is as follows :

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // function for evaluating string length
  5.  
  6. int strlength ( char input[] )
  7. {
  8. int count = 0;
  9. while ( input[count] != '\0' )
  10. ++count;
  11. return count;
  12. }
  13.  
  14. int main(void)
  15. {
  16. int ch, index = 0;
  17. char *input = 0;
  18. char inputBuffer;
  19.  
  20. // procedure for bypassing the junk in stream
  21.  
  22. while ((ch = getchar()) != '\n' && ch != EOF);
  23. fputs ("Enter some text: ", stdout);
  24. while ((inputBuffer = getchar()) != '/n')
  25. {
  26.  
  27. //reallocating taking in consideration the '\0'
  28.  
  29. char* input = (char*) realloc (input, index + 2);
  30.  
  31. if (input == NULL) // mem alloc failed
  32. {
  33. fputs("Memory allocation error", stderr);
  34. exit(1);
  35. }
  36. else
  37. {
  38. input[index++] = inputBuffer; // this is the line bothering me
  39. }
  40. }
  41.  
  42. input[index] = '\0';
  43. printf("The length of the string is %d", strlength(input));
  44. return 0;
  45. }

Hope my third attempt of coding is better than the prev two.
Thanks for always evaluating my code.
Thanks to all for help.
Super Moderator
Featured Poster
Reputation Points: 3241
Solved Threads: 719
Failure as a human
~s.o.s~ is offline Offline
8,873 posts
since Jun 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: Phonebook program!
Next Thread in C Forum Timeline: Convert characters from lowercase to uppercase





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC