0

I am trying to make a function which puts '.' characters in each string of an array, to complete them to n characters. And it is working fine, except that i cannot copy the tmp sting to the string in the array neither with strcpy, nor with pointers. The code is:

void foo (char **t, int count, int n)    {
    int max = 0, i, j;
    char *tmp;
    for (i = 0; i < count; i++) {
        if (max < strlen (t[i]))    max = strlen (t[i]);
    }
    if (max > n)    return;
    for (i = 0; i < count; i++) {
        int diff = n - strlen (t[i]);
        tmp = (char *) malloc (diff * (sizeof (char) * n + 2));
        for (j = 0; j < diff; j++)    {
            tmp [j] = '.';
        }
        tmp [j] = '\0';
        strcat (tmp,t[i]);
        t[i] = (char *) realloc (t[i], strlen (tmp) + 10);
        strcpy (t[i], tmp);
        //*(t + i) = *tmp;  <- I tried this method too
       free (tmp);
    }
}

So it is running well (concatenates the two strings), until the strcpy (t[i], tmp); command. What am I doing wrong?

(I know, I reserve unnecessarily big space, I do it to be sure.)

The main () function in which i use it is:

int main()
{
    char *t[3] = {"string", "foo", "help"};
    int i;
    foo(t, 3, 10);
    for (i = 0; i < 3; ++i)
        printf("%s\n", t[i]);
    return EXIT_SUCCESS;
}

It gives no compiling error, nor warning.

On running it crashes, and returns -1073741819 (0xC0000005), prints nothing.

I am using CodeBlocks.

  • `strcpy` is unsafe because it can be exploited through buffer overflows. – arboreal84 Jun 04 '17 at 09:44
  • It's probable that the t array doesn't have enough space to hold your results. – Malcolm McLean Jun 04 '17 at 09:59
  • 1
    @arboreal84 `strcpy` is perfectly safe if you can prove that its second argument is `\0`-terminated and its first argument has enough space. `t[i] = (char *) realloc (t[i], strlen (tmp) + 10);` suggests this is the case. –  Jun 04 '17 at 10:01
  • 1
    What do you mean with "I cannot copy?". Please, post an [mcve] and the actual output/error. – terence hill Jun 04 '17 at 10:11
  • 2
    Are all of these strings dynamically allocated, to start with?. What @terencehill said, please post an MCVE. –  Jun 04 '17 at 10:15
  • *on a side note*: do not cast `void *` to/from another data pointer type in [tag:c]. for an explanation, [see e.g. here](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –  Jun 04 '17 at 10:17
  • 2
    Use `char* t[3]; t[0] = strdup("string"); t[1] = strdup("foo"); t[2] = strdup("help");` instead – Spikatrix Jun 04 '17 at 10:22
  • 1
    @CoolGuy note `strdup()` is non-standard. To be sure use something like `char *clone = malloc(strlen(str) + 1); strcpy(clone, str);`. –  Jun 04 '17 at 10:23
  • Don't do *x = realloc(x, ...*. It's a bug. – 0andriy Jun 04 '17 at 10:36

0 Answers0