I'm very new here and German, so please excuse my bad English here. As a part of a school exercise we are supposed to implement a socket server with a shared memory for a key-value-store, running on an UNIX-based system. The server, the shared memory and the fork() are working. We use an array of structs and we made functions for this (put, get, delete). In the put-method we get this BAD_ACCESS, when we copy two strings. Code of the method is below, the link to our repository is here: Github Repo
int put(int key, char *value, char *resp){
int emptyIndex = -1;
//strcpy(resp, "");
resp = "";
for(int i = 0; i < STORELENGTH; i++){
// If the key exists, overwrite it, give back previous value, and return true
if(kv[i].key == key) {
resp = kv[i].value;
kv[i].value = value;
return 1;
}
// If the key doesn't exist, remember the empty index
if(kv[i].key == NULL){
emptyIndex = i;
}
}
// If there was an empty index, just reuse it
if(emptyIndex > -1) {
kv[emptyIndex].key = key;
resp = "";
kv[emptyIndex].value = value;
return 1;
}
*resp = (char) "Error: Put was not successful.";
return -1;
}
As you see, the strcpy-Function is a comment, because the programm immediatly stopped working. Thanks for your help, Alex
Assuming, that resp should be a string in your main.c
you are initializing the it incorrectly:
char *resp = ""; <- This one is bad
//char resp[BUFSIZ]; <-- This one is good but commented.
As a result you have a resp
being an char* with allocated size of 1. While strcpy
needs at least size of 2 - one for "" you copy one for "\0" - the string termination character. That's why your app crashes when you try put the length of 2 in the resp whose length is 1 - you are trying to write to the memory you don't own.
Also instead of:
*resp = (char) "Error: Put was not successful.";
You should use the strcpy
also. I would suggest following:
1. Read about the arrays and pointers to understand it better
2. Read documentation for functions you are using if they are new to you, like strcpy. It contains some valuable info like:
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
3. Learn about debugging - imho, it's one of the most important things! For example this link describes some points of memory allocation and debugging techniques.
All this could make your life easier in future :)