簡體   English   中英

導致分段錯誤的語法?

[英]Syntax causing Segmentation Fault?

我下載了一個文本文件,我想讀取一行,刪除前導和跟蹤空白,並將更新的(新)行寫入另一個文件。 我確信有更多雄辯的方法,但我試圖這樣做:

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;
}

我不明白為什么第二種方式造成錯誤? 有人可以幫我解釋一下嗎? 我正在使用lubuntu 14.04 - 這是一個操作系統嗎? 我認為以這種方式使用“math”引用數組中的不同索引是好的嗎?

while( beg <= end ) {
    dst[i] = src[beg];
    i++;
    beg++;
}

這是正確的,因為你推進ibeg並確保beg <= end

while( beg <= end ) {
    dst[i] = src[i + beg];
    i++;
}

在這種情況下,你有一個無限循環,因為如果beg <= end最初是真的,那么在N次迭代之后它總是為真,因為從不修改beg的值。

要糾正它,條件必須確保i + beg <= end (假設你想要[begin,end]范圍而不是[begin,end],這本身並沒有錯)。

[begin, end)范圍的優點是允許您方便地指定基數。
[x, x + 10)表示您的尺寸范圍為10 等價於[x, x + 10 - 1]

您希望范圍的大小是一個簡單的end - begin ,並且您希望包含下限。 [begin, end]意味着您需要對空范圍進行特殊處理,這會產生很多噪音(-1,+ 1,你知道那種)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM