Re: Struggling with libraries




"Flash Gordon" <spam@xxxxxxxxxxxxxxxxxx> wrote in message
news:7b7dh3x9kb.ln2@xxxxxxxxxxxxxxxxxxxxxxxxxx
Fred Kleinschmidt wrote:
"Tony Burrows" <tony@xxxxxxxxxxxxxxx> wrote in message
news:pan.2006.04.17.16.16.32.615585@xxxxxxxxxxxxxxxxxx
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);
Crash! source is not large enough to hold the new characters.

Without the call you don't know that this is the only problem, and in fact
given the additional information the OP has now provided it was not the
only problem.

You need to allocate or reallocate space. What you need is:

char * insert(char* insrt, char* source, int place){
char *temp=NULL;

That initialisation is pointless. In fact, if you move the definition to
after nch you can...

size_t nch = strlen(insrt)+strlen(source)+1;
temp = malloc(nch);

replace the above with
char *temp = malloc(nch);

if ( temp ) {
strncpy(temp, source, place);
temp[place]='\0';
strcat(temp, insrt);
strcat(temp, source+place);
}
return temp;
}

In general, it is the sort of thing I was thinking of. Mind you, I would
not use strcat. You know where you need to copy to (with an additional
variable) so you can use strcpy and save having to scan a potentially long
string. Also I would use memcpy rather than strncpy since you know you are
not copying the entire string. Also one needs to either add error checking
or document it's lack, since if place is beyond the end of source you have
a problem.

I agree that strcat is not the best way, and I would not have used it.
I merely repeated the OP's original code.


Or you could reallocate source

void insert(char* insrt, char** source, int place){
char *temp=NULL;
size_t nch = strlen(insrt)+strlen(source)+1;
temp = realloc(*source, nch);
if ( temp ) {
strncpy(temp, source, place);
temp[place]='\0';
strcat(temp, insrt);
strcat(temp, source+place);
}
else {
/* Decide what to do if the realloc fails */
...
}
}

With the additional information now provided this would not work. We now
know that source is a pointer to a string literal (which you didn't know
when writing this) and so this would still be wrong.

The coding of the insert() method is not wrong here - it is the usage of
that code that is wrong. There's not much that can be done to prevent
a problem if the usage is incorrect.


This shows why the OP should have provided the complete program in the
first place.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project


.



Relevant Pages