Shared memory is sometimes not null finite

// 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 the data does not end with zero and calling strlen (data) calls segfaults ...

So, I tried to make sure it is null-terminated by creating

 data[shm_size] = '\0'; 

But now sometimes it fails in this line of code.

What am I doing wrong?

EDIT: Thanks for your support! I think after your explanation about strlen () + 1 == shm_size, I changed the rest of my code not posted here, and everything seems to be fine. I am waiting for new segfault and hope that I do not get them;)

+4
source share
5 answers

data[shm_size] - one after another. Instead, you should do data[shm_size-1] , and only if shm_size != 0 .

Nevertheless, calling strlen() only makes sense if you really put a string in it. Otherwise, it can return any value < shm_size if the \0 character exists.

+1
source

Arrays 0 -origin, you want:

 data[shm_size - 1] = '\0'; 
+3
source

first: memory should not be zero terminated. it is undefined at the beginning. you may consider using

 memset(data,0,shm_size); 

and second:

 data[shm_size] = '\0'; 

invalid one index. arrays start from scratch, so you should use

 data[shm_size-1] = '\0'; 
+3
source

The purpose of the null termination character is:

 data[shm_size] = '\0'; 

written to the end of the allocated memory, which has undefined behavior . If there is character data of length shm_size in this buffer, then it will be necessary to copy it to another buffer in order to reset it.

+2
source

By making

 `data[shm_size] = '\0';` 

in fact, you are accessing a region of memory outside the boundaries of shared memory ... the syntax of the data[index_value] pointer pointing to the raw block of memory is the same as

 *(data + index_value*sizeof(unsigned char)) 

Thus, data[0] will dereference and return the value at the first memory address in the shared memory segment, and data[shm_size] will do the same and the address beyond the end of the shared memory segment.

+2
source

Source: https://habr.com/ru/post/1397629/


All Articles