'C segfault when modifiy array value [duplicate]
Im getting a segfault when changing dna[i] to U, Ive debbuged but I still cant understand why.
Also I was comparing the value at a position against T with strcmp, but from what I understand thats for string literals and I can simply compare it with dna[i] == 'T'. Is that right? thanks.
#include <string.h>
char *dna_to_rna(char *dna) {
int size = (int)( sizeof(dna) / sizeof(dna[0]));
char *retour[size];
strcpy(retour, dna);
for (int i = 0; i < size; i++) {
if (dna[i] == 'T') {
dna[i] = 'U';
}
}
return (char *) retour;
}
int main() {
char *dna[] = {
"TTTT",
"GCAT",
"GACCGCCGCC"
};
char *actual, *expected;
size_t n;
for (n = 0; n < 3; ++n) {
actual = dna_to_rna(*(dna + n));
}
return 0;
}
Solution 1:[1]
You are passing to the function dna_to_rna a pointer to a string literal
actual = dna_to_rna(*(dna + n));
and then within the function you are trying to change the string literal
if (dna[i] == 'T') {
dna[i] = 'U';
}
Any attempt to change a string literal results in undefined behavior.
Also the expression with the sizeof operator in this declaration
int size = (int)( sizeof(dna) / sizeof(dna[0]));
does not make a sense. It evaluates the size of a pointer of the type char *.
Instead you should use the standard string function strlen.
And this declaration is incorrect
char *retour[size];
At least you need a character array instead of an array of pointers.
char retour[size];
And the function returns a pointer to an array with automatic storage duration that will not be alive after exiting the function
char *dna_to_rna(char *dna) {
//...
char retour[size];
//...
return (char *) retour;
}
that is the function returns an invalid pointer.
You should dynamically allocate a character array within the function with the length strlen( dna ) + 1 and change and return this array.
It seems what you mean is something like the following
#include <string.h>
#include <stdlib.h>
char * dna_to_rna( const char *dna )
{
size_t n = strlen( dna );
char *retour = malloc( n + 1 );
if ( retour != NULL )
{
strcpy( retour, dna );
for ( size_t i = 0; i < n; i++ )
{
if ( retour[i] == 'T' ) retour[i] = 'U';
}
}
return retour;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
