Domanda

#include <stdio.h>
#include <string.h>

int main(void){

char s1[30]="abcdefghijklmnopqrstuvwxyz";

printf("%s\n",s1);

printf("%s",memset(s1,'b',7));

getch();

return 0;
}

Above code works but when I create s1 array like this,

char *s1="abcdefghijklmnopqrstuvwxyz";

it does not give any errors in compile time but fails to run in runtime.

I am using Visual Studio 2012.

Do you know why?

I found prototype of memset is:

 void *memset( void *s, int c, size_t n );
È stato utile?

Soluzione

char s1[30] allocates a writable memory segment to store the contents of the array, char *s1="Sisi is an enemy of Egypt."; doesn't - the latter only sets a pointer to the address of a string constant, which the compiler will typically place in a read-only section of the object code.

Altri suggerimenti

String literals gets space in "read-only-data" section which gets mapped into the process space as read-only (So you can't change it).

char s1[30]="abcdefghijklmnopqrstuvwxyz";

This declares s1 as array of type char, and initialized it.

char *s1="abcdefghijklmnopqrstuvwxyz";

Will place "abcdefghijklmnopqrstuvwxyz" in the read-only parts of the memory and making a pointer to that.

However modifying s1 through memset yields an undefined behavior.

An very good question!.

If you make gcc output the assembly, and compare the output, you could find out the answer, and the following is why:

  • char s1[30]="abcdef";
    • when defined in a function, it will define an array of char, and s1 is the name of the array. The program will allocate memory in stack.
    • when define globally, it will define a object in the program, and the object is not an read only data.
  • char* s2 = "abcdef"; only define a point of char, which point to an const char stored in the .rodata, that is the read only data in the program.

To make program run efficiently and make the progress management easily, the compiler will generate different sections for a given code. Constant chars, like the char* s2 = "abcdef"; and the printf format string will be stored in the .section rodata section. After loading into the main memory by the loader of the OS, this section will be marked as read only. That is why when you use memset to modify the memory which s2 point to, it will complain Segment fault.

Here is an explaination: Difference between char* and char[]

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top