Changing char array values

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

In C, I see the first character of this line:

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

But when I try to change this value:

 foo[0]='f' 

It gives a runtime error.

How can I change these dynamically allocated char array values?

+4
source share
3 answers

You set foo to point to a string literal ( "testing" ), not to allocated memory. Thus, you are trying to change the read only memory of the read only memory, 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 overload vulnerabilities.

+8
source

Your problem is that you are changing the pointer link.

Performing:

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

You assign a pointer to foo on the line "testing" , which is stored somewhere (smokes a runtime error, which I assume), and not on the newly allocated space.

Hope this helps

+2
source

With strings, you should not assign your values ​​with the assignment operator ( = ). This is because strings are not the actual type, they are just char pointers. You should use strcpy instead.

The problem with your code is that you allocated memory for foo , then reassign foo to another memory address, which is READONLY. When you assign foo[0] , you get a runtime error because you are trying to write to read-only memory.

Correct your code by following these steps:

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

This works because foo points to the address you allocated.

+1
source

All Articles