1

I have the below snippets from my code where I am trying to use a dynamically allocated char * array to hold strings coming from stdin.

char **reference
reference = calloc(CHUNK, sizeof(char *));

I am using a temporary static array to first store the string from stdin, then based on a certain condition copy it to the array of char * . I am allocating memory to individual char * in runtime.

                        reference[no_of_ref]=malloc(strlen(temp_in) + 1);
                        reference[no_of_ref++]=temp_in;
//                   printf(" in temp : %s , Value : %s   , Address of charp : %p\n",temp_in,reference[no_of_ref-1],reference[no_of_ref-1]);
                        memset(&temp_in,'\0',sizeof(temp_in));
                        pre_pip = -1;
                }

        /*If allocated buffer is at brim, extend it by CHUNK bytes*/
                if(no_of_ref == CHUNK - 2)
                        realloc(reference,no_of_ref + CHUNK);

so no_of_ref holds the total number of strings finally received. e.g 20. But when I print the whole reference array to see each string, I get the same string that came last , getting printed 20 times.

1 Answer 1

3

Here of your code introduces the problem:

reference[no_of_ref]=malloc(strlen(temp_in) + 1);
reference[no_of_ref++]=temp_in;

That's because assignment of pointers in C affects pointers and only pointers, which won't do anything with its contents. You shall use things like memcpy or strcpy:

reference[no_of_ref]=malloc(strlen(temp_in) + 1);
strcpy(reference[no_of_ref], temp_in);
no_of_ref+=1;
2
  • Bahh... This is something I am aware of, and still forget everytime I work with char * copying. Thanks for reminding again..!! Nov 4, 2013 at 4:13
  • @DiwakarSharma it's quite a pleasure to help :)
    – starrify
    Nov 4, 2013 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.