?
Solved

extracting part of a string???

Posted on 2003-02-19
19
Medium Priority
?
321 Views
Last Modified: 2010-04-15
Hi,

I've got a function:

int func(char*whole, char*locator)

What I'm wanting inside this function, is for the string 'whole' to be searched for the string variable 'locator' and for the string to be extracted up until the locator is reached and put into a variable. I've tried the following with no success:

int examiner(char *whole, char *locator)
{
        char *V1, compostemp;
        int compos;
       
     compostemp = strchr(line,locator);
     compos = atoi(compostemp);
     strncpy(V1,whole_line,compos);
        cout << V1 <<endl;
         
     return 0;
}

Although that's just a mess... :) Can anybody do a bit of intervening?

Thanks
Uni
0
Comment
Question by:Unimatrix_001
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 2
  • +1
19 Comments
 
LVL 6

Expert Comment

by:gj62
ID: 7983501
BTW - you look like you are using C++ - there are other ways to do this, but here is a C way...

int examiner(char *whole, char *locator, char *result)
{
  char * p;
  strcpy(result,whole);
  p = strstr(result, locator);
  if (p)  /* we found the string */
  {
     *p=0;
  }
  else
  {
  /* what do you want to do if the substring was not found */
  }
}
0
 
LVL 6

Expert Comment

by:gj62
ID: 7983540
The above assumes a few things.

First, that result is at least as big as whole.  
Second, that you wanted the partial string copies into a new location, and not just to truncate whole.

Now, in your code, you do the following:

char * v1;
...

strncpy(v1....);

This is a bug.  v1 is merely a pointer - there is no storage associated with the pointer.  By copying a string into that pointer, you are overwritting who-knows-what in memory.

0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7984105
I've tried the above, although just a few points:

does it matter that I'm declaring result as "char *result" inside of the function rather than it being passed to the function as one of its arguments?

Also, it compiles ok, but it crashes on the:

     strcpy(result,whole);

Complaining that the referenced memory at "0xccccccccccc" couldn't be written.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7984113
btw...in reference to your:

"Now, in your code, you do the following:

char * v1;
...

strncpy(v1....);

This is a bug.  v1 is merely a pointer - there is no storage associated with the pointer.  By copying a string into that pointer, you are overwritting who-knows-what in memory."


How do I get past this problem and copy the thingy from strncpy into V1?
0
 
LVL 6

Expert Comment

by:gj62
ID: 7984447
You have to pass in 3 strings - whole, locator and result.

For example:

char whole[100]; /* will hold 99 characters plus NULL */
char result[100];
char locator[20];

strcpy(whole, "Some string data to test with");
strcpy(locator, "test");
examiner(whole, locator, result);
printf("result = %s\n", result);

gotta run, will follow up in a little while...
0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7984475
hrm...I'm not quite sure I explained myself properly... The code you've given me searches the string for the locator, however I then want to extract from 'whole' the text all before the locator, assuming that the locator is found and I then want to extract the remains of the 'whole' (i.e. from the locator onwards) into a new variable.

Thanks again
0
 
LVL 6

Expert Comment

by:gj62
ID: 7984515
OK, so to explain things a bit.

As you are probably aware, there really isn't a 'string' type in C.  What you have are arrays of characters.  When the array is null-terminated, you can work on those arrays using the string manipulation functions provided in the C runtime library.

So,

char myString[100];  creates an array of 100 characters.  At most, you should store 99 actual characters, leaving the last space for the null.  myString is actually a pointer to the array, *myString will return the first character in the array, myString[0] will also return the first character.

char *myString;  creates a pointer to an array of characters - but there is no storage space allocated for those characters.  myString should not be used until either (a) you create space, or (b) you assign myString a value where space is created.

For example:

char *myString;
myString = (char *)malloc(100);

does the same thing as

char myString[100];

Another example:

char oneString[] = "This is a test string";
char *myString;

myString = oneString;

What this does is set myString to point at the same string that oneString is pointing at - it DOES NOT copy the string.  myString and oneString just point at the same area of memory.  Therefor, the following is true:

printf("%s", myString); would print "This is a test string"

strcpy(oneString,"New String Here");

printf("%s", myString); would now print "New String Here"
0
 
LVL 6

Expert Comment

by:gj62
ID: 7984548
OK, my first function did the reverse of what you wanted, I believe- in that it returns the first part of the string - up to locator.  

The following will put everything after the locator in the result string (you must have allocated space for result by declaring it with storage, or using malloc() etc:  If this is not what you need, please provide specific examples using a test string.

int examiner(char *whole, char *locator, char *result)
{
 char * p;
 p = strstr(result, locator);
 if (p)  /* we found the string */
 {
    strcpy(result, p+strlen(locator));
 }
 else
 {
 /* what do you want to do if the substring was not found */
 }
}

In this function, p contains no storage - it is merely a pointer assigned to the place in whole where locator is found by strstr().  'result' must storage associated to it:

char result[100], or something like it, before calling examiner.

This assumes you know how much at compile time.  If you don't, then you have to malloc() space for it during run time.  Remember, however, that if you are in a loop, successive calls to malloc() will reserve new areas of memory and not release the old memory - unless you call free().  This would cause a memory leak...
0
 
LVL 8

Accepted Solution

by:
ssnkumar earned 90 total points
ID: 7985385
Unimatrix_001,
I have modified your function a bit and made it work for you. I have also written a main program to test it. I am attaching the code below. You can compile/execute/test it and see if this is what you were looking for:

#include <stdio.h>
#include <string.h>

int examiner(char *whole, char *locator)
{
    char *V1, *compostemp;
    int compos;

    compostemp = strstr(whole, locator);

    compos = (int)compostemp - (int)whole;
    V1 = (char *) malloc(100);
    strncpy(V1,whole,compos);
    printf("%s\n", V1);

    return 0;
}

main()
{
    char *whole = (char *) malloc(100);
    char *part = (char *) malloc(25);;

    strcpy(whole, "My name is Unimatrix_001");
    strcpy(part, "mat");

    examiner(whole, part);
}
0
 
LVL 6

Expert Comment

by:gj62
ID: 7986788
Unimatrix,

You should know that every time you call the function that ssnkumar has written:

1) Every time you call the function, you are allocating 100 bytes of storage which cannot be freed.  This is the definition of a memory leak and a very bad bug.

2) You do not get the result of the function - it only prints that string, you cannot access it from the main.

3) This function assumes that the return string will never be longer than 100 chars.  If it is, it will overwrite memory and cause another bug.

At a minimum, if you know that 100 bytes is enough, and that printing the result string is all you want to do, you should at least change the definition of v1 to char v1[100]; and not use malloc(), or put free(v1); before you exit the function...
0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7987047
Hiya,

Thanks for your responses...I've tried your code ssnkumar and it works a treat except that when I copy some string that is less than 100 characters I get loads of daft characters at the end of the string i.e:

   strcpy(whole, "My name is Unimatrix_001");
   strcpy(part, " ");

I get:

  "My======================================================bnafu;pbf"

Things like that, any ideas?

Thanks
Uni
0
 

Expert Comment

by:modulo
ID: 7987132
Points changed from 50 to 30 by CS request:
http://www.experts-exchange.com/Community_Support/Q_20522261.html

modulo

Community Support Moderator
Experts Exchange
0
 
LVL 6

Expert Comment

by:gj62
ID: 7987293
add the line

V1[compos]=0;

AFTER the line

strncpy(V1,whole,compos);


So here is what is should look like:

   strncpy(V1,whole,compos);
   V1[compos]=0;               /* add this line */
   printf("%s\n", V1);


NOTE that this is still a very bad implementation due to memory leaks...
0
 
LVL 6

Expert Comment

by:gj62
ID: 7987314
add the line

V1[compos]=0;

AFTER the line

strncpy(V1,whole,compos);


So here is what is should look like:

   strncpy(V1,whole,compos);
   V1[compos]=0;               /* add this line */
   printf("%s\n", V1);


NOTE that this is still a very bad implementation due to memory leaks...
0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7988421
to just sort out the memory leaks can I just use

free(v1)

at the end of the function as gj62 suggested?
0
 
LVL 6

Expert Comment

by:gj62
ID: 7988895
you can either use free, or you can declare v1 as follows:

char V1[100];

That space is allocated, and then freed, automatically on the stack when the function is called and is preferred IF you know how much you need to allocate at compile-time.

Generally, you wouldn't use malloc() inside a function that only allocates 100 bytes for the duration of a small function.

You would normally only use malloc if (a) the storage requirements weren't known at compile time, or (b) you wanted the space allocate off the heap and not the stack.
0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7989172
Thank you!!! :D I'm going to accept ssnkumar's comment here and I'll post another one for you!

Thanks again to both of you!
Uni
0
 
LVL 3

Author Comment

by:Unimatrix_001
ID: 7989186
A good because it was the other guy who actually helped explain your code a bit :)

Thanks
Uni
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 7991512
gj62,
I have only given a sample program. Yes, garbage collection has to be taken care of..... And may be many more things!

Unimatrix_001,
Sorry for late response!:-(
>"My======================================================bnafu;pbf"
The reason for garbage is that, it's not initialized.
When you declare array or allocate memory to a char pointer, you can initialize all the values to zero using bzero() or to any value using memset(). Both of these need string.h file to be included.
And as gj62 has pointed out, you have to free the memory allocated using malloc() or use a automatic variable such as array.

Anyway, thanks for giving points to me too:-)
And thanks to gj62 for pointing out the loophole....:-))

-Narendra
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question