user3706129
user3706129

Reputation: 229

wrong copying into struct

I am passing string into struct , i am doin it like this inside for loop

printf("copy = %s\n",copy_p);
str[i].string=(char*)malloc(strlen(copy_p)+1 * sizeof(char));
strcpy(str[i].string,copy_p);
printf("skop = %s\n" , str[i].string);

So if copy_p variable is "Program has stopped working" this is what happens

printf("copy = %s\n",copy_p); // copy = Program has stopped working
printf("skop = %s\n" , str[i].string); // skop = Program has stopped working

But if i call this printf("%s\n",str[0].string) it outputs Program has stopped work! why is that? but it isnt like this all the time it works for the most of the inputs

Upvotes: 1

Views: 56

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

This line is incorrect regardless of the type of copy_p:

str[i].string=(char*)malloc(sizeof(copy_p)+1 * sizeof(char));
  • If copy_p is an array of characters initialized with a string literal, i.e.

    char copy_p[] = "Program has stopped working";
    

    then +1 is unnecessary, because array size already includes null terminator.

  • If copy_p is a pointer char *copy_p, then you need to call strlen instead of sizeof, i.e.

    str[i].string=malloc(strlen(copy_p)+1 * sizeof(char));
    

Note: casting results of malloc is unnecessary in C.

Upvotes: 6

Related Questions