user3741086
user3741086

Reputation: 125

Add zeros to String in C

I want to add zeroes in front of a string with this method:

void addFrontzeros(char *str,int zeros)
{
    if(zeros==0)
    {
        return;
    }

    char *temp=malloc((strlen(str)+1+zeros)*sizeof(char));

    int i=0;
    for(;i<zeros;i++)
    {
        temp[i]='0';
    }

    int j=0;
    for(;j<strlen(str);j++)
    {
        temp[j+zeros]=str[j];
    }
    temp[strlen(str)+zeros]=0;
    str=realloc(str,(strlen(temp)+1)*sizeof(char));
    strcpy(str,temp);
    free(temp);
}

But when i call it from another Method the string is empty after the invocation. The caller string is allocated like this in another method:

char *mul = malloc(sizeof(char)*2);
    mul[0]='0';
    mul[1]=0;

With valgrind i got this error: Address 0x5201b00 is 0 bytes inside a block of size 2 free'd

I think the problem is with realloc , but i don't have an idea why it wont work here

Upvotes: 0

Views: 1263

Answers (1)

hobbs
hobbs

Reputation: 240274

By calling realloc you're (possibly) modifying str inside the function, but the caller of addFrontzeros doesn't see the new value of str. It still has the old version of str which no longer points to valid data after the realloc.

Your function should either return str (so that it can be called as x = addFrontzeros(x, n)) or accept a char ** so that it can modify the pointer in place.

As pointed out by StoryTeller, str = realloc(str, ...) is unsafe in the case where realloc fails. First, because you're not testing whether realloc returned NULL, and second, because if it does return NULL, you have a memory leak because the old str is still allocated but you've lost your pointer to it. A minimal way to handle it would be

char *new_str = realloc(str, strlen(temp)+1);
if (!new_str) {
    perror("addFrontzeros: realloc");
} else {
    str = new_str;
}

although if you want to handle the failure in some other way, you can, and the original str will still be valid and unmodified.

Another problem is that you only copy strlen(str) bytes, which doesn't include the terminating zero byte, so your string is not correctly terminated. Either add the terminating zero yourself, or simply copy one more byte (since you can assume str is correctly terminated to start with).

Finally, as a side note, sizeof(char) is 1 by definition, so multiplying by it is unnecessary.

Upvotes: 5

Related Questions