This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Memcpy corrupts the data in memory, allocated by calloc function.

Other Parts Discussed in Thread: MSP430F67791

I am using MSP430F67791 to control a GSM module. My memory usage is

18688 bytes of CODE memory

10417 bytes of DATA memory (+ 232 absolute)

1141 bytes of CONST memory

So total of 30246 bytes used. And remaining memory is 2522 bytes of memory.

I am doing following operations.

unsigned char* msg = calloc(strlen("hello")+1, sizeof(unsigned char));

memset(msg, 0, strlen("hello")+1);

memcpy(msg,"hello", strlen("hello"));

Here the word 'hello' is corrupted.

Please tell me the reason for corruption. Am I exceding memory. My heal size is 3000.

  • Vishnu Prasaad said:
    So total of 30246 bytes used. And remaining memory is 2522 bytes of memory.
    [...]
    My heap size is 3000.

    So this wouldn't work out a tall (heap size > available memory).
    However, the code size doesn't count for ram memory usage. code is placed and runs from flash memory (which is 512kB). So your available space is ~22k

    However, did you check the returned msg? If calloc fails for some reason, it will be 0. Using it then, will cause all kind of havoc, the first byte being corrupted is the least problem you then have.

    I noticed that you use "hello" three times as constant. Depednign on the compiler and ocmpiler settings these may be three different instances of "hello". It would be a waste of space.
    Using
    "const unsigned char hello[] = "hello";"
    and then using this in the code, would be clearer.

    Now I don't know whether memcpy does a word-wise copy. If so, if msg or the constant "hello" are not word aligned, a corrupted byte at start or end would be the natural cause.
    This would of course be a bug, since memcpy is supposed to copy at byte granularity. But maybe some optimization in the memcpy code is not working.

    Other than that, I don't have an idea. (btw: which compiler are you using? IAR? CSS? MSPGCC? Which version?)

    And finally: how do you know the word is corrupted? Maybe the problem is somewhere else and you only think it is memcpy.

**Attention** This is a public forum