Andrei Andrei - 1 month ago 7
C Question

Problems with strcat

I have a weird problem with

strca
t in C. This is the code:

char *getip(char n[])
{
char *x[255];
strcat(x, n);
char *ip;
ip = strtok(x, "/");
return ip;
}

char *adrr(char n[])
{
char *ip[255];
strcat(ip, getip(n));
return ip;
}

int main(void)
{
scanf("%s", &n);
printf("IP : %s\n", getip(n));
printf("IP : %s", adrr(n));
}


The first
printf
returns exactly what I want it to return, and although the function
adrr
does seemingly nothing, the second
printf
returns some random character at the beginning and the end of what it should return.

Answer

There are many problems in your code:

  • you define x in getip as char *x[255], it should be char x[255]
  • you should initialize x before calling strcat or use strcpy.
  • ip points to the local array x, returning it to the caller invokes undefined behavior as the array it points to cannot be used after the function returns.
  • same problems in adrr()
  • n is not defined in main for scanf("%s",&n);

The first function seems to work as expected out of pure luck, it may fail when compiled on a different system, or even just on a different day ;-)

Here is a solution:

#include <stdio.h>

char *getip(char *dest, const char *src) {
    for (i = 0; src[i] != '\0' && src[i] != '/'; i++) {
        dest[i] = src[i];
    }
    dest[i] = '\0';
    return dest;
}

int main(void) {
    char n[256];
    char ip[256];

    if (scanf("%255s", n) == 1) {
        printf("IP: %s\n", getip(ip, n));
    }
    return 0;
}
Comments