Alessandroempire Alessandroempire - 4 months ago 25
C Question

Transforming from char * to char[]

I am getting segmentation fault in the following code

static char * result;

char s[31];

int i;

random_string(s, 10);



// for (i = 0; i < 15; i++){
// result[i] = s[i];
// }

strcpy(result, s);

printf("el result es %s\n", result);


where the function random_string is:

void random_string(char * string, int length)
{
/* Seed number for rand() */

int i;

for (i = 0; i < length -1; ++i){

string[i] = rand() % 90 + 65;
}

string[length] = '\0';
}


For some reason I am getting segmentation fault when using strcpy. Also copying byte by byte is not working. What is the problem? I am out of ideas.

Answer

static char * result; is just an address without any allocated memory!

Try this: [EDITED]

char * result = (char*)malloc(strlen(s) + 1);
Comments