Re: Inconsistent Program Results
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Tue, 06 Mar 2007 23:20:59 +0000
Francine.Neary@xxxxxxxxxxxxxx said:
I am learning C, having fun with strings & pointers at the moment!
The following program is my solution to an exercise to take an input,
strip the first word, and output the rest. It works fine when you give
it 2 or more words, but when there's only 1 word the results vary
depending on whether it's on Windows or Linux: under MSVC it displays
no output (as it should); under gcc/Linux it instead gives
"Segmentation fault".
Any ideas what's going on?
TIA!
#include <malloc.h>
Replace this with <stdlib.h> which is the standard header you need when
using malloc.
#include <stdio.h>
This is fine.
#include <memory.h>
Replace this with <string.h> which is the standard header you need when
using strchr.
#define LEN 1000
void rdinpt();
Make this:
void rdinput(char **);
Incidentally, readinput would have been a better name.
void main()
Make this:
int main(void)
{
char *s, *restrict;
rdinpt(&s);
restrict=strchr(s,' ');
If the malloc fails, s will have the value NULL, which is not legal for
passing to strchr.
If there is no space in the input string, strchr will return NULL, which
you must not pass to printf to match %s, and which you must not
increment.
printf("%s\n", ++restrict);
free(s), s=restrict=0;
This made me reach for the book. Simplify:
free(s);
s = restrict = 0;
return (0);
return 0;
is fine. The return keyword is not a function name.
}
void rdinpt(char **s)
{
*s=(char *) malloc( (unsigned int) LEN);
Better:
*s = malloc(LEN * sizeof **s);
The general form is: p = malloc(n * sizeof *p);
(void) gets(*s);
Avoid gets() - it cannot be used safely. Instead, use:
fgets(s, LEN, stdin);
return(0);
Remove this, since rdinpt doesn't return a value.
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
.
- Follow-Ups:
- Re: Inconsistent Program Results
- From: Francine . Neary
- Re: Inconsistent Program Results
- References:
- Inconsistent Program Results
- From: Francine . Neary
- Inconsistent Program Results
- Prev by Date: Re: regarding multidimensional arrays
- Next by Date: Resumes CV's / Positive vs. Negative Thinking Free Informational Site
- Previous by thread: Inconsistent Program Results
- Next by thread: Re: Inconsistent Program Results
- Index(es):
Relevant Pages
|