 |
Linux Format forums Help, discussion, magazine feedback and more
|
| View previous topic :: View next topic |
| Author |
Message |
TonyLB LXF regular
Joined: Tue Apr 12, 2005 8:08 pm Posts: 111 Location: Wirral, UK
|
Posted: Mon Apr 17, 2006 5:19 pm Post subject: C functions and libraries |
|
|
I'm just learning C as another language, and I'm trying to build some utilities into a library. I have this (crude I know) function:
void insert(char* insrt, char* source, int place){
char temp[strlen(insrt)+strlen(source)+1];
strncpy(temp, source, place);
temp[place]='\0';
strcat(temp, insrt);
strcat(temp, source+place);
strcpy(source, temp);
}
In a simple file, it all works, but in a static library, when I call it I get a segnmentation fault. The villain is the final strcpy.
I tried returning temp instead and that doesn't work either, I don't get quite the string that exists in the function (and the compiler warns about returning a local variable).
I know there's a solution, I just have no idea what it is. Any help would be great.
Tony |
|
| Back to top |
|
 |
Nigel LXF regular

Joined: Fri Apr 08, 2005 9:03 pm Posts: 1141 Location: Gloucestershire, UK
|
Posted: Tue Apr 18, 2006 9:33 am Post subject: RE: C functions and libraries |
|
|
OK, I think the answer lies in how you are calling the routine. Are you doing something like this...
| Code: | char string1[1024];
char string2[1024];
char *str1;
char *str2;
str1 = "I believe it";
str2 = "DON'T ";
insert (str2, str1, 2); |
If so, the segfault is because you have changed the pointer str1 to point to the literal "I believe it" instead of the character array string1. It is not legal to write to a string literal.
The calling sequence should be something like this :
| Code: | char string1[1024];
char string2[1024];
char *str1;
char *str2;
strcpy (str1,"I believe it");
strcpy (str2,"DON'T ");
insert (str2, str1, 2); |
_________________ Hope this helps,
Nigel. |
|
| Back to top |
|
 |
TonyLB LXF regular
Joined: Tue Apr 12, 2005 8:08 pm Posts: 111 Location: Wirral, UK
|
Posted: Wed Apr 19, 2006 6:07 pm Post subject: RE: C functions and libraries |
|
|
Thanks, yes.
In fact, in my original code I'd uses a char array which was passed to insert, and the later version user a char* instead, which seems to be the problem at least in part since there was no room for the inserted characters.
Tony _________________ In the beginning was nothing, which exploded! (Lords and Ladies, Terry Pratchett) |
|
| Back to top |
|
 |
| View previous topic :: View next topic |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|
|