Home > Net >  Copy a section of a string into buffer in C
Copy a section of a string into buffer in C

Time:11-22

I have a char buffer[ 32 ]; and there is a sourceString, which I'm not sure how it is defined, but I don't think it matters.

sourceString is "abcdefgh"

To copy "cdef" it into the buffer I make use of snprintf:

snprintf( buffer, 4 1, "%s", sourceString 2 );

where 4 is the size of the copied section and 2 is the index of the first character in the section

It works, but I am worried about a few things causing a problem:

  1. Buffer size is bigger than the string. Does it hurt to have some slack there?
  2. sourceString 2 doesn't modify the sourceString or does it? I don't understand how exactly this works.
  3. Are there any risks of memory leaks in this solution?

CodePudding user response:

  1. You are wasting a bit of memory here in byes (32 - (4 1)) = 27. It's ok to do, and a fairly common technique both for a compile-time allocation like there, or a run-time allocation. Do, however, use a #define instead of your magic 4, 2 and 32 numbers:
#define BUFFER_LEN 32
#define SOURCE_SUBSTR_LEN 4
#define SOURCE_OFFSET 2

char buffer[BUFFER_LEN];
...
  1. No, it simply calculates an address that is 2 elements from the start of the string. You can also express this as &sourceSring[2] if you wish.

  2. No. Memory leaks usually implies heap allocated memory (malloc, realloc, calloc) and buffer[32] is allocated at compile time (on the stack).

Consider using strncpy (or memcpy) instead of snprintf.

  • Related