C functions and libraries

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

C functions and libraries

Postby TonyLB » Mon Apr 17, 2006 4:19 pm

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
TonyLB
LXF regular
 
Posts: 112
Joined: Tue Apr 12, 2005 7:08 pm
Location: Wirral, UK

RE: C functions and libraries

Postby Nigel » Tue Apr 18, 2006 8:33 am

OK, I think the answer lies in how you are calling the routine. Are you doing something like this...
Code: Select all
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: Select all
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.
User avatar
Nigel
LXF regular
 
Posts: 1141
Joined: Fri Apr 08, 2005 8:03 pm
Location: Gloucestershire, UK

RE: C functions and libraries

Postby TonyLB » Wed Apr 19, 2006 5:07 pm

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)
TonyLB
LXF regular
 
Posts: 112
Joined: Tue Apr 12, 2005 7:08 pm
Location: Wirral, UK


Return to Programming

Who is online

Users browsing this forum: No registered users and 2 guests

cron