views:

87

answers:

2

I have a C program which loads a file line-by-line into one string and then memcpy's this string into another string pointer using this code:

   typedef struct inmod_struct {
       Int32 ReturnCode;
       Int32 Length;
       char  Body[ROWSIZE];
    } inmdtyp,*inmdptr;

    inmdptr inmodptr;
    char line[600];
    int doit()
    {
        char *p;
        p = inmodptr->Body;
        ReadFile();  //reads a line of the file into **line** string variable


    memcpy(p, line, strlen(line));
    p += strlen(line);

    inmodptr->ReturnCode = 0;
    inmodptr->Length = p - inmodptr->Body;

    reccnt++;
}

But when I execute the above program on my Windows XP SP3 machine, I get an error message box saying:

The instruction at "<memory address>" referenced memory at "<memory address>". The memory could not be "written". Click OK to terminate....

I faced similar problem when I tried to do similar memory operations it is giving similar problems. strcpy works best for me but strcpy omits reads till NUL character of the line but I will have some more characters to be read even after NUL in the line. Can anybody please provide a workaround or any soultion for this.

Environment: Windows XP SP3, GCC compiler.

I even tried similar code compiling and usage on solaris unix and I am facing same issue there.

I have been facing similar errors with some of the OpenCV Python, C samples also.

Edit: Sorry guys.. I have that pointer p initialized p = inmodptr->Body; inmodptr is a structure. and I can confirm that the pointer initialization is not the issue. Posted the full code for clarity

+2  A: 

You need to allocate a buffer and have p hold the address of that buffer. Then you can use p like you did.

A pointer is a variable that holds a memory address. Your pointer holds some uninitialized value which probably doesn't point to a valid memory address.

char *p = malloc(strlen(line) + 1);

If you are storing a string the extra +1 is for the NULL terminated char \0. If you are using memcpy instead of strcpy for some reason, you'll have to manually NULL terminate your buffer.

Also if you malloc be sure to free once you are done using it. You could also simply stack allocate an array of characters and use that instead of p.

Brian R. Bondy
the OP should also not forget to free the memory "free(p);"
celavek
@Marius: As mentioned yes.
Brian R. Bondy
A: 

This line:

inmdptr inmodptr;

declares a pointer inmodptr, but doesn't initialise it - it's pointing at some random memory location.

You need to make it point somewhere that can hold an actual instance of the struct inmod_struct object - for example:

inmdtyp inmod;
inmdptr inmodptr = &inmod;
caf