Home > Net >  strcpy in C is illegally altering the copied string?
strcpy in C is illegally altering the copied string?

Time:08-07

This is a really mysterious behavior I can't get around.

I'm trying to edit the string of one variable and then copy again to the source. I have the following code:

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

int main() {
    char word[100] = "1 hash";
    char* sp = malloc(100);
    sp = strchr(word, ' ');
    sp  ;
    // the "bug" still happens with strcpy  instead of strncpy
    strncpy(word, sp, 100);

    printf("%s\n", word);
}

The output is:

hhsh

It should've been hash.

The weird thing is that "1 hash" is the only string I found that this bug happens. All the other strings I tried gave me the expected output. For example: "1 huhanh" -> huhanh or "3 a h c" -> a h c

Any help would be greatly appreciated.

CodePudding user response:

You have undefined behavior. The malloc pointer is ignored.

So, when you do the strcpy, sp and word are part of the same string.

This is UB. Which means it may segfault. It may work. It may produce incorrect results.

Here is the corrected code:

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

int
main()
{
    char word[100] = "1 hash";
    char *copy = malloc(100);

    char *sp = strchr(word, ' ');
    sp  ;

    // the "bug" still happens with strcpy instead of strncpy
    strncpy(copy, sp, 100);

    printf("%s\n", copy);
}

CodePudding user response:

char* sp = malloc(100);

The problem is that this allocated memory is not used, at all. strchr returns a pointer to a character in the original string. And according to the documentation

destination and source shall not overlap

CodePudding user response:

this code

char* sp = malloc(100);
sp = strchr(word, ' ');

allocates some memory then leaks it away. sp ends up pointed into the 'word' on the stack

  • Related