Alessandroempire
Alessandroempire

Reputation: 1699

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.

Upvotes: 0

Views: 148

Answers (6)

Dmitry Sazonov
Dmitry Sazonov

Reputation: 8994

You forgot to allocate memory to "result" pointer. Try next:

result = malloc( strlen( s ) + 1 );
strcpy(result, s);

Upvotes: 2

&#181;tex
&#181;tex

Reputation: 908

Declare result as a char array like static char result[10];

or assign some memory to result pointer.

Upvotes: 0

Leo Chapiro
Leo Chapiro

Reputation: 13984

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

Try this: [EDITED]

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

Upvotes: 2

nemo
nemo

Reputation: 57619

You need to assign a valid memory region to your result pointer using malloc or using static memory, as you are doing with your s string. Otherwise your pointer has just a random location assigned and your program receives a segfault by accessing it as it lies out of the boundaries of your program.

Upvotes: 0

suspectus
suspectus

Reputation: 17258

result is just a uninitialised pointer. You must assign result to a character buffer before using strcpy.

Upvotes: 0

Mark Wilkins
Mark Wilkins

Reputation: 41222

The problem is that result has not been initialized. It results in undefined behavior. Before it can be used like that, you need to make sure it points to a valid buffer. For example:

result = malloc( strlen( s ) + 1 );

Upvotes: 4

Related Questions