MarkM
MarkM

Reputation: 857

C strcpy into an array of strings in shared memory

I want (or need) to do something along the lines of

char **my_array = malloc(1000*64);
strcpy(arr[0], "test");

While I know that arr[0] isn't pointing to a separate piece of allocated memory, I thought one should be able to copy a string into it like this (yet it segs). This works

arr[0] = "test";

However that is not going to work, for my actual goal is to do this in shared memory.

shm_array = shmget(IPC_PRIVATE, 1000 * 64, IPC_CREAT | 0644);
my_array = (char**) shmat(shm_array, (void**)0, 0);

Actually my question could be rephrased to: "How do you create an array of strings in shared memory?". I tried creating 1000 separate "string" shared memory segments, but apart of that it did not work it also seems wrong. Moreover, I thought one should simply be able to write into a big shared memory segment using relative pointer offsets.

Upvotes: 0

Views: 2656

Answers (3)

caf
caf

Reputation: 239171

If you want to dynamically allocate an array of 64-character arrays, then use a pointer to an array rather than a pointer to a pointer:

char (*my_array)[64] = malloc(1000 * sizeof my_array[0]);
strcpy(my_array[0], "test");

or for the shared-memory case,

shm_array = shmget(IPC_PRIVATE, 1000 * sizeof my_array[0], IPC_CREAT | 0644);
my_array = shmat(shm_array, NULL, 0);

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

It looks like you are looking for a 2D array 1000 by 64. If this is indeed the case, you can do this:

struct shared_1000_by_64 {
    char strings[1000][64];
};

struct shared_1000_by_64 *shared = malloc(sizeof(struct shared_1000_by_64));
for (int i = 0 ; i != 1000 ; i++) {
    strcpy(shared->strings[i], "test");
}

This uses the standard trick of preventing the array from decaying into a pointer.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477368

You could just create one single piece of memory and write to specific offsets:

char * const buf = malloc(HUGE);

strcpy(buf + offset1, "hello");
strcpy(buf + offset2, "world");

It'd probably be better to use strncpy and pass a size of HUGE - offset along to make sure you don't run over the end. Managing the offsets is your own responsibility. Or you can use strncat, if efficiency doesn't matter so much.

Upvotes: 1

Related Questions