user2858814
user2858814

Reputation: 11

C strings malloc (output)

I have some strange output here. Could you explain me why and how to solve it?

int inp_str(char * string, char ** pointers[])
{
    char * tmp[stringsCount];
    if (strlen(string) > maxlen)
    return (-1);
    else {
    tmp[count] = malloc(sizeof(char) * strlen(string));
    strcpy(tmp[count], string);
    pointers[count] = &tmp[count];
    count++;
    }
    return count;

}


int main(){

    //char * strings[stringsCount];
    char ** pointers[stringsCount];
    inp_str( "sdasya", pointers);
    inp_str( "dasd", pointers);
    inp_str( "qwe", pointers);
    inp_str( "dasd", pointers);

    //sort(pointers, count);
    printf("%s", *pointers[0]);
    printf("\n%s", *pointers[1]);
    printf("\n%s", *pointers[2]);
    printf("\n%s", *pointers[3]);
}

Here is output:

sdasya
��uNH��H�l$ H�\$L�d$(L�l$0H��8�f.�
qwe
�bs7

PS. stringsCount is constant; count = 0

Upvotes: 1

Views: 141

Answers (3)

Jens
Jens

Reputation: 72697

In addition to losing the tmp[] pointer after the function returns, you're also always allocating one byte short of the actual amount needed: strlen(s) returns the length of a string, which does not include the terminating NUL byte. What you need is (note that sizeof(char) is 1 by definition):

  char *p = malloc(strlen(string) + 1);
  strcpy (p, string);

to duplicate a string.

Upvotes: 0

Jamie
Jamie

Reputation: 76

I'm not sure I understand what you're trying to do here. But in any case, there are a few problems:

1) You're copying string into an uninitialized pointer. I.e. you create an array of (char *)'s which point to anywhere and you then copy the string to that location. If you're trying to point tmp to your string, don't use strcpy, just assign via tmp[count]=string;

2) tmp is created on the stack, so if you assign its value to pointers** and try to reference the address outside of the scope of this function, that memory is gone and you will likely see corrupt data.

Hope this helps. Out of curiosity, what are you trying to do in this function?

Upvotes: 0

CS Pei
CS Pei

Reputation: 11047

Because char * tmp[stringsCount]; is a local variable, after the function inp_str returns, the memory of tmp is reclaimed by the system. So the pointers to that location are invalid after the function returns.

Upvotes: 3

Related Questions