organismLee
organismLee

Reputation: 15

Does malloc use the data or text segment or another type of memory?

char *p1 = "hello";
char *p2 = (char *)malloc(10 * sizeof(char));
char *p3 = "bye";

strcpy(p2, p1);
printf("p2:%s, %p\n", p2, p2);

strcpy(p2, p3); 
printf("p2:%s, %p\n", p2, p2);

Upvotes: 0

Views: 584

Answers (1)

RalfFriedl
RalfFriedl

Reputation: 1130

You tagged the question with C without reference to any operating system or CPU.

The concepts of data segment and text segment are not related to C, they are related to some operating systems that make this distinction.

Of course, as the text segment, on systems that use it, is for code and read-only data, and the memory returned by malloc can be modified, it can't be the text segment.

The data segment can refer to the initialized data, malloc of course allocates new data, so it can't be this meaning of data segment.

If your definition of data segment is any data, then the returned memory is part of that. There are some (uncommon/old) architectures with separate code and data address spaces.

The C standard only promises that the malloc memory is modifiable and properly aligned.

Upvotes: 3

Related Questions