spatara
spatara

Reputation: 901

Why does memcpy not work on second try?

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?

Upvotes: 0

Views: 910

Answers (2)

Mike Housky
Mike Housky

Reputation: 4069

The only possible culprits in this case seem to be:

(1) malloc() fails--you didn't check for a NULL result

(2) a prior corruption has scrambled things.

You can get a segment fault by reading memory, so a third option might be added if the source argument is not 0-terminated and the fault occurs before finding a readable 0 byte (and before overrunning the 500-char receiving array causes other problems.) That can't happen with those short string literals, so anything like this would have to fall under (2).

Your snippet, hacked into a main program (memory leak and all) didn't fail for me. (See hnhzflep's answer for a more exhaustive demo-that-doesn't-blow-up.

Upvotes: 3

enhzflep
enhzflep

Reputation: 13089

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++;
    }
}

Upvotes: 1

Related Questions