Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a char array's values

Tags:

arrays

c

pointers

char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";

In C, i can see the first character of that string :

printf("%c",foo[0]);

But when i try to change that value :

foo[0]='f'

It gives error in runtime.

How can i change this, dynamically allocated, char array's values?

like image 432
platypus Avatar asked Dec 22 '22 14:12

platypus


1 Answers

You are setting foo to point to the string literal ("testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory.

This is the correct code:

char* foo = malloc(sizeof(char)*50);
strcpy(foo,"testing");

or even better

cont int MAXSTRSIZE = 50;
char* foo = malloc(sizeof(char)*MAXSTRSIZE);
strncpy(foo,"testing",MAXSTRSIZE);

to protect against buffer over-run vulnerability.

like image 100
Hogan Avatar answered Jan 08 '23 16:01

Hogan