why strncpy fails?

If I run the function and strncpy the program breaks. I cannot find out why. The char * var is "". The pointer refers to C string 88469-88471. I need to copy the 88469-88471 to the var. Notice that complete string is x:88469-88471 ...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
LIMITS1 getNumberFromRegex(std::string s, char ch)
{
char * var = "";
const char * cs = s.c_str();
LIMITS1 limits;
limits.min=0; limits.max=0;

if ( cs[0]==ch ){
	if ( isdigit(cs[1]))
		{
		cs+=1;
		var = strncpy(var, cs, strlen(cs)-1);
		}
	else
		if ( !isdigit(cs[2]))
			error("", 2);
		else 
		{
			cs+=2;
			var = strncpy(var, cs, strlen(cs)-1);
		}
	limits.min = (int) strtok(var,"-");
	if ( limits.min != NULL)
		limits.max = (int) strtok(var,"-");
	return limits;
}
return limits;
}


The strncpy is broken during execution. It is some problem with the var. I got error in strncpy.asm, as it tried to assign value to var:

1
2
3
4
src_misaligned:
        mov     al,byte ptr [esi]   ; copy a byte from source to dest
        add     esi,1
        mov     [edi],al  ; <-- here it breaks.


Notice:
I have also tried this:
1
2
cs+=2;
errort = strcpy_s(var, strlen(cs)-1, cs);

With the same effect. The program also breaks.
Last edited on
You need to read the warnings

I told you already, 'var' is pointing to a const char*
And even if you could write there you have not reserved enough space.


http://www.cplusplus.com/faq/sequences/strings/split/
Last edited on
I have solved it with this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* Written by Niels Möller <nisse@lysator.liu.se>
 *
 * This file is hereby placed in the public domain.
 */

#include <stdlib.h>
#include <string.h>

#include <memory.h>
#include <stdio.h>
char * strndup (const char *s, size_t size)
{
  char *r;
  char *end = (char *) memchr(s, 0, size);
 
  if (end)
    /* Length + 1 */
    size = end - s + 1;
 
  r = (char *) malloc(size);

  if (size)
    {
      memcpy(r, s, size-1);
      r[size-1] = '\0';
    }
  return r;
}


Used like so:
var = strndup(cs+2, strlen(cs)-1 ); // works similar like substr - using malloc
Topic archived. No new replies allowed.