1

I have two equal strings, I need to delete a portion of one of them, and store it in another.

My code is not working:

int main(int argc, char *argv[])
{
    char *imagetmp = argv[1];
    char *imagefile = imagetmp;
    char *unpackdir = imagetmp;

    // Remove substring from char imagefile
    char * pch;
    pch = strstr (imagefile,".img");
    strncpy (pch,"",6);

    // Print strings
    puts (imagefile);
    puts (unpackdir);
    return 0;
}

Here is the expected output:

./imgtools mysuperimage.img
mysuperimage.img
mysuperimage

Here is the actual output:

./imgtools mysuperimage.img
mysuperimage
mysuperimage

How can I fix this?

1
  • 2
    The both pointers point to the same string. So changing the string using one pointer gives the same result accessing the string using another pointer. You need to make a copu of the original string if you need to keep two separate strings. Commented Mar 24, 2020 at 17:45

1 Answer 1

2

You will need to make a copy of argv[1], if you have two pointers to the same string they will naturally print the same:

int main(int argc, char *argv[])
{
    char imagefile[100];
    if(argc < 2) {
       puts("Too few arguments");
       return 1;
    }

    strncpy(imagefile, argv[1], sizeof(imagefile) - 1);
    //char *unpackdir = argv[1]; you can use argv[1] directly

    // Remove substring from char imagefile
    char * pch;
    if((pch = strstr (argv[1],".img")))
        *pch = 0; //or '\0', just null terminate the string, it's simpler 
    else
        puts("Extension not found");

    // Print strings
    puts (imagefile);
    puts (argv[1]);
    return 0;
}
Sign up to request clarification or add additional context in comments.

7 Comments

@yano, well spotted, thks.
If the program's 1st argument is longer then 99 characters to program runs into undefined behaviour due to a buffer overflow. Not nice.
@alk, yes, you are correct, I was thinking the same, corrected it.
You can't use strstr correctly unless you check the return. If there is no ".img" in argv[1], then pch == NULL -- which while strncpy should be smart enough to handle the error, but is something best avoided. Simply if ((pch = strstr (argv[1], ".img")) *pch = 0; will work, no strncpy required. (but the problem with "20200324.img-event.img" would remain....)
That's better, good job. Might explain that copying 6-spaces (or empty-string -- whichever it is) to overwrite the extension probably isn't the best way to go when you can just nul-terminate at pch with a simple assignment and remove the extension :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.