Search code examples
cstringoverwritestrcpy

How to prevent strcpy from overwriting another variable as well?


I'm trying to make a simple code that converts one type of data into another. I use strtok to extract one part of the data and then I run a long serial of if conditions to find the right output. However, when the correct output is found and written in the variable currentNote, it also seems to overwrite the variable comma for a reason I can't figure out. Here is the problematic part of the code :

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

int main()
{
    char sequence[] = "c1[M],c1[M],d3[L],c3[M],b2[M],(#A-2)[IKN],(#A-1)[L]";
    char copy[] = "";
    char *comma;
    char currentNote[4] = "";

    strcpy(copy, sequence);

    comma = strtok(copy, ",");

    if(strstr(comma, "c1") != 0)     //c1
        {
                printf("%s\n\n", comma);          //Here ...
                strcpy(currentNote, "C5 ");
                printf("%s\n\n", comma);
        }
    return 0;
}

And here's the outcome :

c1[M]

cC5

No need to say that strcpy(currentNote, "C5 "); is causing it. I don't know why though, I thought it would return c1[M] like I would like it to do. After some more experimentation it turns out that the secondprintf("%s\n\n", comma); will always return the first character of sequence followed by C5. I hope someone can find out, it would be very great.


Solution

  • You are calling
    strcpy(copy, sequence) while copy is a 1 element length array. You need to define it by giving it sufficient size. Your code as is, is simply a UB. Redefine it like

    char copy[100];

    Or allocate sufficient memory to it dynamically using malloc.