C/C

Advertisement


Question
QUESTION: hii
i have a question regarding c . like see
main()
{
int *p="amit";
p[0]='h';
printf("%s",p);
this prgm works fine with turbo c but  when i used gcc as my compiler it compiled ok but as i run ,it gives segmentation fault .i m using gcc on linux machine . upto my knowledge we r try to access memory loction that is nt meant for us (readonly).but why its working ok on turbo c(windows).is this issue is related operating system means how windows and linux handles memory .
i will be very thankful to u to response.....

ANSWER: I believe you are correct that the linux machine puts the string "amit" into read only memory. I have experienced this myself on other occasions. If you intend to modify the string, you should do a strdup, or create a local array of the string like this:

char p[] = "amit";

Also note that you are declaring p as a pointer to an integer. An integer is 4 bytes long, when you say p[0]='h' it will replace 4 bytes of the string. You will get 1 byte of the h character, and three zero bytes. Where the zeros and 'h' byte end up will depend how you machine stores integers. On an intel machine the least significant byte is placed at the lowest address.

I hope that helps you.

Best regards
Zlatko


---------- FOLLOW-UP ----------

QUESTION: THANKS 4 responding..
but zlatko don't u think it has something to do with operating system..
means the windows and linux handles memory...because segmentation comes under memory management.. and i think linux is somewhat more strict to memory violation. i really would like you to highlight how memory managed by os..

Answer
Hello Amit.

Yes, I agree with you. I think it is because Linux places the string in the code segment so it cannot be modified. I think Windows does not have the the same restriction. This site may give you more information
http://linuxgazette.net/112/krishnakumar.html

Try this program (modified form the above site) on a Linux system, and see where the pString points to. It may give you a clue. I don't have a Linux machine to try it on.

I have not been able to find out how Windows organizes its process memory.

#include <stdio.h>
#include <stdlib.h>

int our_init_data = 30;
int our_noinit_data;

int main()
{
   int our_local_data = 1;
   char* pString = "asdfg";

   printf("init data   = %p\n", &our_init_data);
   printf("uninit data = %p\n", &our_noinit_data);
   printf("code        = %p\n", &main);
   printf("stack       = %p\n", &our_local_data);

   printf("string      = %p\n", pString);
   printf("heap        = %p\n", malloc(1));
   return 0;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.