It's ok my question is already answered here: http://cboard.cprogramming.com/showthread.php?t=110612 in post #5. Sorry for the repost
Hi,
I am writing some code to parse a port range given as a string eg: "20-25". After I figure out where the first port ends and I try to copy it however I get a segfault:
Code:
if( ( dash = strchr(ports, '-')) != NULL )
{
/* port range given */
int index = dash - ports;
if(index < 0)
index = -index;
char *temp;
fnshPort = atoi( (dash + 1) );
strncpy( temp, ports, index ); /* here is the segfault */
strtPort = atoi(temp);
Code:
Breakpoint 1, main (argc=3, argv=0xbfbf5e84) at starshine.c:59
59 strncpy( temp, ports, index ); /* here is the segfault */
(gdb) print temp
$1 = 0xb80e9e00 "U\211�WVS�p\207"
(gdb) print ports
$2 = 0xbfbf7c13 "20-25"
(gdb) step
Program received signal SIGSEGV, Segmentation fault.
0xb7fee41c in strncpy () from /lib/libc.so.6
The pointer arithmetic is copied from a website, but it makes sense to me. What has me stumped is that if I declare temp as an array it works fine, both lines below fix the problem:
I tried the later one but gdb shows that it doesn't get declared any smaller than the first, which was my intention, is using a number the only decent way to do it? index is 2 for the above example of "20-25".
So my question is: why doesn't a plain old c string work?