Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

C program displaying more characters than array size

I've written a small program to concatenate a string "20746865" upto 300 characters. The program is as follows:

#include<stdio.h>
#include<string.h>

void main()
{
char test[] = {'2','0','7','4','6','8','6','5'};
char crib[300];
int i, length = 0;
 while(length <= 299)
  {
     for(i=0; i<8;i++)
      {
        crib[length] = test[i];
        i=i%8;
        length++;
      }

  }
crib[length]='';
printf("%s", crib);
}

The following is the output:

2074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865207468652074686520746865

However, when i count the number of characters in the output, it shows 304 characters. Could someone help me understand how can it print 304 characters if the array size is only 300?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The bug in your code is that the inner loop continues even when the written index is out of bounds, which causes it to continue until the next multiple of 8 generating undefined behavior.

Unlike previous replies, this version compiles and works according to your description using C99, minimizing the number of copies and iterations.

#include <stdio.h>
#include <string.h>

static const size_t OUTPUT_SIZE = 300U;
static const char   INPUT[]     = {'2','0','7','4','6','8','6','5'};
static const size_t INPUT_SIZE  = sizeof(INPUT);

int main()
{
    char output[OUTPUT_SIZE + 1];
    const size_t numIter = OUTPUT_SIZE / INPUT_SIZE;
    size_t idx = 0;

    // copy full chunks
    for (; idx < numIter; idx++)
    {
        memcpy(output + idx * INPUT_SIZE, INPUT, INPUT_SIZE);
    }

    // write the remainder
    memcpy(output + numIter * INPUT_SIZE, INPUT, OUTPUT_SIZE % INPUT_SIZE);

    // add null terminator
    output[OUTPUT_SIZE] = '';

    printf("result: %s
length: %d
", output, strlen(output));

    return 0;
}

I hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...