Reputation: 19
I downloaded a text file, I want to read a line, chop the lead and trail whitespace, and write the updated (new) line into another file. I'm sure there are more eloquent ways of doing, but I'm trying to do it this way:
char *make_dst( char *src, int beg, int end ) {
char *dst = ( char * )malloc( MAXLEN * sizeof( char ));
int i = 0;
if( dst != NULL ) {
while( beg <= end ) {
/* this works fine */
dst[i] = src[beg];
i++;
beg++;
/* this causes the segmentation fault */
dst[i] = src[i + beg];
i++;
}
dst[i] = '\0';
return dst;
}
I don't understand why the second manner of doing it causing the error? Can anybody explain this for me? I'm using lubuntu 14.04 - is it an operating system thing? I thought it was fine to use "math" in that manner to reference different indexes in an array?
Upvotes: 1
Views: 91
Reputation: 16540
the following code will go the job
char *make_dst( char *src, int beg, int end )
{
int i = 0;
char *dst = malloc( MAXLEN);
if( NULL == dst )
{ // then malloc failed
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
memset( dst, 0x00, MAXLEN );
for( i=0, i<(end-beg+1); i++ )
{
dst[i] = src[beg++];
} // end for
return dst;
} // end function: make_dst
Upvotes: 0
Reputation: 9071
while( beg <= end ) {
dst[i] = src[beg];
i++;
beg++;
}
This is correct because you're advancing both i
and beg
and assuring that beg <= end
.
while( beg <= end ) {
dst[i] = src[i + beg];
i++;
}
In this case, you have an infinite loop, because if beg <= end
was true initially, it will always be true after N iterations since the value of beg
is never modified.
To correct it, the condition must ensure that i + beg <= end
(This is assuming you want [begin, end] ranges instead of [begin, end), which is not wrong, per se).
[begin, end)
ranges have the advantage of allowing you to specify cardinality conveniently.
[x, x + 10)
means you have a range of size 10
. The equivalent is [x, x + 10 - 1]
.
You want the size of the range to be a simple end - begin
, and you want to include the lower bound. [begin, end]
means you need special handling for empty ranges, and it would incur a lot of noise (-1, +1, you know the kind).
Upvotes: 3