Juan Torres Juan Torres - 1 month ago 10
C Question

char[] vs char* in scanf C when writing memory

I'm trying to use a

char*
data type to store a string from user, the code compiles fine but it fails when executing the
scanf
instruction,
a fixed array
char[10]
works smoothly but I'd like to know how can I use a
char*
instead.

bouclesCon.c

#include "bouclesCon.h"
/... ... ...
void func_While(){
//char message[10] ="hey" ;//good
char*message="hey";//copiles but fails to execute
while(strcmp(message,"sortir")!=0){
printf("vous avez ecrit %s\n",message);
scanf("%s",message);
}
}


main.c

#include"bouclesCon.h"
int main()
{
func_While();
return 0;
}


UPDATE

As explained by carveone and Igor , the problem was related to the allocation of enough memory when using a char pointer(char*) to write a user input at runtime through scanf(), in constrast an array handles the memory differently.

SOLUTION working code :

`void func_While(){
//char message[10] ="hey" ;//good
char*message="hey";//copiles and execute fine!!
message=malloc(10);
if(message==NULL){
printf("error\n");
}else{
while(strcmp(message,"sortir")!=0){
printf("vous avez ecrit %s\n",message);
scanf("%s",message);
}
}
free(message);
}
`

Answer

As Igor Tandetnik says precisely in his comment, attempts to write to memory occupied by a string literal exhibit undefined behavior.

Thus the line:

char*message="hey";

is the problem. The string "hey" is likely in read-only memory but might not be - the compiler could theoretically allocate 4 bytes on the stack and point message to it. In which case you could write 4 bytes before smashing your stack.

It's best not to guess and use:

const char*message="hey";

If you need to write to message, either use an array like you already have done; pointers and arrays are interchangeable (but not identical, see the C FAQ), or allocate an appropriate amount of memory:

char *message;

message = malloc(100);    /* 100 bytes allocated */
if (message == NULL)      /* The allocation failed */
   ...error...

/* Write to message */

free(message);     /* Free the 100 bytes */
Comments