problems with char * return from a function

John Love-Jensen eljay@adobe.com
Mon Jun 16 12:45:00 GMT 2008


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



More information about the Gcc-help mailing list