I was debugging a program and following is the snapshot:

81				while (j < len_y && suf_arr[j].word[0] == c)
(gdb) 
184					if (suf_arr[j].len > 1)
(gdb) n
186						memcpy(temp_str, suf_arr[j].word+1, suf_arr[j].len-1);
(gdb) n
187						ind = search(suf_arr, temp_str, len_y);
(gdb) print suf_arr[j].word
$13 = 0x7fffffff96d2 "bbit"
(gdb) print suf_arr[j].word+1
$14 = 0x7fffffff96d3 "bit"
(gdb) print suf_arr[j].len-1
$15 = 3
(gdb) print temp_str
$16 = "bitt", '\000' <repeats 10005 times>

As you see I am copying the substring starting from second character onwards into temp_str. From the print statements you can see that the original word and the all the parameters are within range.

word element is a pointer which is pointing to some other string ie the word is not malloc-ed. So not part of the array of structures (suffix_ds below):

for (j = 0;j < len_y;j++)
168                 {
169                         suf_arr[j].word = &y[j];
170                         suf_arr[j].len = len_y-j;
171                 }
172 
173                 // sort
174                 sort(suf_arr, len_y);
175 
176                 for (j = 0;j < len_y;j++)
177                 {
178                         c = suf_arr[j].word[0];
179                         begin = j;
180 
181                         while (j < len_y && suf_arr[j].word[0] == c)
182                         {

Structure of suf_arr is

typedef struct
  7 {
  8         char* word;
  9         int count;
 10         int prev;
 11         int len;
 12 } suffix_ds;

suffix_ds suf_arr[MAX];

Why is it not acting correctly?

Why is it not acting correctly?

Probably because your length parameter is shy by one. Try not subtracting 1:

memcpy(temp_str, suf_arr[j].word+1, suf_arr[j].len);

You still want to copy the null character, after all.

memcpy seems to be doing exactly what it was asked to do, ie. copy exactly 3 characters, 'b' 'i' 't', on top of a buffer which already contains 5 characters, 'b' 'b' 'i' 't' '\0' (note the null terminator).
Only the first 3 characters are changed.
To include the terminator, copy 4 characters (suf_arr[j].len)
instead of 3 (suf_arr[j].len-1).

commented: good help +28
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.