cstructstrcpy

c - strcpy with struct string returning error


I have 2 ip addresses of the form xxx.xxx.xxx.xxx stored as 4 integers xxx (0-255) in a structure.

I have successfully converted the integers to strings, and backfilled with '0' so I can compare the two.

i.e. 1 => 001 , 96 => 096

However, I am having trouble storing the string to my structure when exiting my function and cannot see my error as everything is defined.

My code:

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

struct ipToStr{
    char ip1Str [4];
    char ip2Str [4];
    char ip3Str [4];
    char ip4Str [4];
};

void backfillZero(int ip, char *saveTo){
    char tempIp [4];
    char zeros [4];

    sprintf(tempIp, "%i", ip);
    int nDigits = strlen(tempIp); 

    while(nDigits < 3){
        strcat(zeros, "0");
        nDigits += 1;
    }

    strcat(zeros, tempIp);

    printf("Backfiled: %s\n",zeros);

    strcpy(saveTo, zeros); //causes error
}

void main(){
    char filledIp [13]; //after calling this function 4 times, I'll use strcat and 
                        //this string to store the whole ip, then conver to int
                        
    struct ipToStr *backfilledIp;

    backfillZero(12, backfilledIp->ip1Str);

    printf("ip: %s\n", backfilledIp->ip1Str); 
}

Solution

  • Main problem:

        struct ipToStr *backfilledIp;
        backfillZero(12, backfilledIp->ip1Str);
    

    backfilledIp pointer is not initialized and it is not referencing valid memory. It is undefined behaviour.

    1. instead of this weird function backfillZero simply do sprintf(saveTo, "%03d", ip);
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    struct ipToStr{
        char ip1Str [4];
        char ip2Str [4];
        char ip3Str [4];
        char ip4Str [4];
    };
    
    void backfillZero(int ip, char *saveTo, size_t size)
    {
        snprintf(saveTo, size, "%03d", ip);
    }
    
    void main(){
        char filledIp [13]; //after calling this function 4 times, I'll use strcat and 
                            //this string to store the whole ip, then conver to int
                            
        struct ipToStr backfilledIp;
        struct ipToStr *backfilledIp1 = malloc(sizeof(*backfilledIp1));
    
        backfillZero(12, backfilledIp.ip1Str, sizeof(backfilledIp.ip1Str));
        printf("ip: %s\n", backfilledIp.ip1Str); 
    
        if(backfilledIp1)
        {
            backfillZero(25, backfilledIp1 -> ip1Str, sizeof(backfilledIp1 -> ip1Str));
            printf("ip: %s\n", backfilledIp1 -> ip1Str); 
        }
        free(backfilledIp1);
    }
    

    https://godbolt.org/z/4fKehajnM