A qtcreator program on Linux crashes with a "segmentation fault" error.

int segment_id; int shmid; char* shared_memory; struct shmid_ds shmbuffer; const int shared_segment_size = 0x500000; segment_id=shmget(IPC_PRIVATE,shared_segment_size,IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR); shared_memory = (char*)shmat(segment_id,0,0); sprintf(shared_memory, "dfdsf"); shmctl(shmid, IPC_STAT, &shmbuffer); printf("\n Размер выделенного блока:%d", shmbuffer.shm_segsz); shmdt(shared_memory); shared_memory = (char*) shmat(segment_id, (void*)0x6400,0); printf("\n Сегмент переподключения адреса %p", shared_memory); printf("%s",shared_memory); shmdt(shared_memory); shmctl(segment_id,IPC_RMID,0); 

Tell me what's wrong, I do not really understand it.

  • Have you ever heard of a "minimal example that reproduces a problem"? Try it out. - KoVadim
  • What are the pointers segment_id and shared_memory to by chance not NULL ? - ߊߚߤߘ
  • I do not know. It seems that segment_id should be assigned an identifier. - Andrei
  • Removing the line printf ("% s", shared_memory); it all worked. Do not quite understand why. - Andrei

1 answer 1

Problem in reconnecting memory shared_memory = (char*) shmat(segment_id, (void*)0x6400,0);

You do not have to check returnable codes, so the program continues to run even after an error in shmat . In the event of an error, shmat() returns -1 , and when you try to print a string at this address, a seg fault occurs.

Alas, I can’t name the cause of the shmat error, because I don’t know the physics of using the parameters shmaddr and shmflg , but my system reports "wrong arguments":

  shared_memory = (char*) shmat(segment_id, (void*)0x6400,0); if ((void *) -1 == shared_memory) { printf ("error shmat, errno=%s\n", strerror(errno)); return 0; } 

erno displays as Invalid argument and -1 remains in shared_memory .