Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Memory sometimes not null terminatied

// reading                        
if((shmid = shmget(key, 0, 0)) < 0) {                  
    perror("shmget");                
    exit(50); 
}                                                         

// attach                                                 
if((data = shmat(shmid, (void *)0, 0)) == (char *) -1) {        
    perror("shmat");                                      
    exit(100);                                            
}

// get memory size
struct shmid_ds shm_info;
size_t shm_size;
int shm_rc;
if((shm_rc = shmctl(shmid, IPC_STAT, &shm_info)) < 0)
    exit(101);
shm_size = shm_info.shm_segsz;

Sometimes data is not null terminated and calling strlen(data) causes segfaults...

So I was trying to make sure that it is null terminated by making

data[shm_size] = '\0';

But now sometimes it fails on that line of code.

What I'm doing wrong?

EDIT: Thanks for your support! I think after your explanation about the strlen() + 1 == shm_size I have changed the rest of my code not posted here and seems to be fine. I'm waiting for new segfaults and hopefully I will not get any ;)

like image 453
edo888 Avatar asked Dec 22 '22 01:12

edo888


1 Answers

Arrays are 0-origin, you want:

data[shm_size - 1] = '\0';
like image 67
ouah Avatar answered Dec 24 '22 00:12

ouah