Today I finished the music project, or at least I think I've finished it. On helper.c when I run make it makes both notes and synthesizer files and with no errors. But when I want to run ./notes it gives me segmentation fault error. Even when I ran the program with check50 it gave me this error:
failed to execute program due to segmentation fault
I personally think it might be because of turning string to int or the way I got the notes from the string. First I introduced one string for taking the note and one int for taking the ovtav of the note.
The string note is something like D4 or C#4
So I will just copy this part, to check with you if I've done it correctly.
string noteletter="";
int noteoctav;
if (strlen(note) == 3)
{
noteletter[0] = note[0];
noteletter[1] = note[1];
noteoctav = note[2] - '0';
}
if (strlen(note)== 2)
{
noteletter[0] = note[0];
noteoctav = note[1] - '0';
}
Here I've added the full code so you can see what I am trying to do.
Two problems I can see (assuming string
is a typedef of char*
)
if noteletter
has a length of 0 (value = ""
) then what do you think noteletter[1]
is doing?
Even if noteletter
was set to something bigger (eg noteletter = "ABC";
) - writing to a literal string is undefined behavior.
Try char noteletter[3] = { 0 };
to get something that (at a quick glance) looks big enough.
Another possible issue: if note
is NULL
or invalid then strlen(note)
is not safe.
(Posted answer on behalf of the question author)
My problem was that I defined noteletter as string. I changed that part to
char noteletter[4];
int noteoctav;
if (strlen(note) == 3)
{
noteletter[0] = note[0];
noteletter[1] = note[1];
noteletter[2] = '\0';
noteoctav = note[2] - '0';
}
if (strlen(note)== 2)
{
noteletter[0] = note[0];
noteletter[1] = '\0';
noteoctav = note[1] - '0';
}
and now it works :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.