[SOLVED]"Segmentation fault" error with "strncpy" function in

Hello, guys! I'm trying to get a substring of a string in C and i'm using strncpy function to do this. The compilation doesn't show any error message, but when i try to run the program, i have a "Segmentation fault" error message in terminal! I'm using Debian with Gcc-4.7.
1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include<string.h>
int main() {
	char *time = "09:34";
	char *min = strncpy( min, time+3, 2 );
	printf("-> %s \n", min );
	  
	return 1;
}


What am i doing wrong?
Last edited on
Should be:

1
2
3
4
5
6
7
#include <stdio.h>
#include<string.h>
int main() {
	char *time = "09:34", *temp, *min = strncpy( temp, time+3, 2 );
	printf("-> %s \n", min );
	return 1;
}


you might want to stick to c++ copying methods than the single-minded c functions

E: Interesting. The above works, but the one he made and this do not...can anyone say why?
1
2
3
4
5
6
7
8
#include <stdio.h>
#include<string.h>
int main() {
	char *time = "09:34", *min;
	min = strncpy( min, time+3, 2 );;
	printf("-> %s \n", min );
	return 1;
}
Last edited on
For me, of your way is not working too.
@robgeek
@Smac89


The both code snips

the first one

1
2
	char *time = "09:34";
	char *min = strncpy( min, time+3, 2 );

and the suggested modification

char *time = "09:34", *temp, *min = strncpy( temp, time+3, 2 );

are invalid and contain the same error.

First of all pointers to string literal should be declared with the const qualifier because neither C nor C++ allow to modify string literals.

So instead of

char *time = "09:34";

there should be written

const char *time = "09:34";

Secondly both of you are trying to copy the original string literal to a memory with an arbitrary address becuase neither min nor temp were properly initialized.

So the valid code will look the following way


1
2
3
	const char *time = "09:34";
	char min[3];
	strcpy( min, time+3 );


or

1
2
3
	const char *time = "09:34";
	char min[3] ={ '\0' };
	strncpy( min, time+3, 2 );


or


1
2
3
	const char *time = "09:34";
	char *min = ( char * )malloc( 3 * sizeof( char ) );
	strcpy( min, time+3 );


or

1
2
3
4
	const char *time = "09:34";
	char *min = ( char * )malloc( 3 * sizeof( char ) );
	strncpy( min, time+3, 2 );
	min[2] = '\0';



vlad and smac89. Thanks for your help. Now everything is working fine!
Topic archived. No new replies allowed.