Home > Enterprise >  Converting int list to string - C
Converting int list to string - C

Time:05-30

I was trying to convert a list of integers into a compact string but I get a segmentation fault. The code is the following:

    int *factors = job_factorization(number, size);
    char buffer[250] = { 0 };

    for (int i = 0; i < *size; i  ) {
        sprintf( &buffer[i],  "%d ", *factors);
        factors  ;
    }

The job_factorization function returns the head of the list (it works, I have already tested it), and it sets the value pointed to by size to the actual size of the list (so the number of integers). I cannot figure out what is wrong, does anyone have any idea?

CodePudding user response:

Note these remarks:

  • sprintf( &buffer[i], "%d ", *factors); does not convert the number at the end of the previous conversion.

  • sprintf does not check for buffer overflow: if size is large enough, it will eventually write beyond the end of the buffer.

  • modifying factors is probably not a good idea as this pointer should be freed after use.

Here is an alternative:

    int *factors = job_factorization(number, size);
    char buffer[1024];
    size_t pos = 0;

    for (int i = 0; pos < sizeof buffer && i < *size; i  ) {
        pos  = snprintf(buffer   pos, sizeof buffer - pos, "%d ", factors[i]);
    }

You could also use 2 loops to compute the size needed for the conversion and allocate the space needed.

  • Related