memcpy is behaving in a strange way in my program. My function is called twice, so the memcpy line is run twice, the first time it works no problem and the second time around I get a seg fault at that line (using gdb). I am confused because I don't understand why it would work once but not twice...also, the two names I input are the same length.
This is what I have...
typedef struct _item_
{
char name[500];
}item;
int my_function(char *name)
{
item *myitem = malloc(sizeof(item));
char* temp = myitem->name;
strcpy(temp, name);
/* code here to write add item to a global structure */
return 0;
}
in testing code...
int i;
i = my_function("test1");
.
.
.
i = my_function("test2");
Then i changed it to strcpy and the same problem occurs
strcpy(temp, name);
Any ideas as to why this might not be working?
Oh, okaaay then. Well, you need to look at your code. Specifically at what the destination pointer you give memcpy or strcpy is pointing to. Your message clearly indicates that you're trying to write to memory you don't own. Here's a minimal compilable version that uses the code you supplied. It works just fine. 20,000 times the function is called and a valid result returned. This is verified when all 20,000 elements are printed out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _item_
{
char name[500];
}item;
item *my_function(char *name)
{
item *myItem = (item*)malloc(sizeof(item));
strcpy(myItem->name, name);
return myItem;
}
int main()
{
const int max = 10000; // 10,000 iterations
item *itemList[max*2]; // 2 operations per loop iteration
int j, index = 0;
for (j=0; j<max; j++)
{
itemList[index++] = my_function("test1");
itemList[index++] = my_function("test2");
}
index = 0;
for (j=0; j<max; j++)
{
printf("%d. - %s\n", 1+index, itemList[index]->name);
index++;
printf("%d. - %s\n", 1+index, itemList[index]->name);
index++;
}
}