On Friday 11 May 2012 14:06:03 David C. Rankin wrote:
Guys,
I need a bit of help. I've tried to follow the example after wchar_t * wcscat that explains why using mempcpy is better than using strcat or wcscat, but I run into a segmentation fault attempting to use the suggested mempcpy replacement. The code in libc.html (Ver: 2.15) is shown below. I had to add the declaration for 's' to get past an undefined error (should have told me something right then).
char * concat (const char *str, ...) { va_list ap; size_t allocated = 100; char *result = (char *) malloc (allocated);
if (result != NULL) { char *newp; char *wp; const char *s; ^^^^^^^^^^^^^^^^^^
va_start (ap, str);
wp = result; for (s = str; s != NULL; s = va_arg (ap, const char *)) { size_t len = strlen (s);
/* Resize the allocated memory if necessary. */ if (wp + len + 1 > result + allocated) { allocated = (allocated + len) * 2; newp = (char *) realloc (result, allocated); if (newp == NULL) { free (result); return NULL; } wp = newp + (wp - result); result = newp; }
wp = mempcpy (wp, s, len); }
/* Terminate the result string. */ *wp++ = '\0';
/* Resize memory to the optimal size. */ newp = realloc (result, wp - result); if (newp != NULL) result = newp;
va_end (ap); }
return result; }
I created a simple test program to verify the code:
#include
#include #include #include #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif
/* combine strings efficiently */
char * concat (const char *str, ...);
int main (int argc, char **argv) {
char * myS1 = "This is the beginning"; char * myS2 = " of my string to test"; char * myS3 = " libc manual concat."; char * result;
fprintf ( stderr, "myS1: %s\nmyS2: %s\nmyS3: %s\n", myS1, myS2, myS3);
result = concat( myS1, myS2, myS3 ); fprintf ( stderr, "The result is: %s\n", result);
return 0; }
The compiler issues 2 warning (obviously the problem) that I cannot fix?
13:55 alchemy:~/dev/prg/ccpp/src-c/io/file> gcc -Wall -oct contest.c contest.c: In function ‘concat’: contest.c:61:4: warning: implicit declaration of function ‘mempcpy’ contest.c:61:9: warning: incompatible implicit declaration of built-in function ‘mempcpy’
The man page (on 11.4) shows the exact same use of mempcpy:
void *mempcpy(void *dest, const void *src, size_t n);
The runtime failure is on the line: 'wp = mempcpy (wp, s, len);' (the if is skipped due to length < 100 of all strings). I like the idea of sticking with the gnu libc guidance of using mempcpy instead of strcat or wcscat, especially with the manuals labeling of programmers that use strcat "as lazy and reckless", but if the suggested replacement doesn't work...
So what gives here? What am I not seeing? What say the gurus?
Isn't "memcpy" one of those dangerous copying routines? -- To unsubscribe, e-mail: opensuse+unsubscribe@opensuse.org To contact the owner, e-mail: opensuse+owner@opensuse.org