Re: problems with char * return from a function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Vardan,

Eus said...
 
> It looks like that you have not zeroed your `a'.
> `a[0]='\0';' is not enough.
> Either you do `char a[BUFFER_SIZE] = {0};' when defining `a' or, better, you
> do `memset(a, 0, BUFFER_SIZE);'

For strcpy, it should not be necessary to zero the 'a'.

For a strcat, just a[0]='\0'; should be sufficient to make 'a' strcat-able.

For C, I like Eus' suggestion:  char a[1024] = { 0 };

For C++, you can omit the first element:  char a[1024] = { };

However, for the problem as presented, is necessary to actually allocate the
buffer for 'a'.

These won't work:

char* a = NULL; // a does not actually refer to any space.
strcpy(a,x("sample text","default text")); // ERROR!

char* a; // a has a garbage pointer
strcpy(a,x("sample text","default text")); // ERROR!

char a[5]; // Not enough space.
strcpy(a,x("sample text","default text")); // ERROR!

- - - - - -

These will work:

char a[1024]; // Overkill, but will work. 'a' is on the stack.
strcpy(a,x("sample text","default text"));

char* a;
a = malloc(1024); // Overkill, but will work. Note#1
strcpy(a,x("sample text","default text"));

char* temp = x("sample text","default text");
char a = malloc(strlen(temp)+1); // Exact allocation. Note#1.
strcpy(a, temp);

Note#1: Be very mindful of the ownership & lifespan of 'a' which was
allocated off the heap.  Remember to free(a) when done with it.

HTH,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux