Andrei
Andrei

Reputation: 31

Problems with strcat

I have a weird problem with strcat 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.

Upvotes: 1

Views: 982

Answers (2)

chqrlie
chqrlie

Reputation: 144550

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

Upvotes: 3

chris01
chris01

Reputation: 12311

  1. n in main does not exist
  2. I think you think about char buf[10] but write char *buf[10]
  3. If you return a pointer to a memory that only exists inside a function than the result is undefined. Make it static or dynamic.

Upvotes: 0

Related Questions