Weird variable behaviour

23 Sep 2012

Hi,

I've stumbled upon a very weird problem with the C24LCXX_I2C library to read/write to an EEPROM.

Writing works fine but when I try to read strings, using the stripped method underneath here, it usually fails with the I2C read returning 40. Meanwhile I figured out it has something to do with the length. When I change the p_length2write variable to hardcoded number 4 (to read the string "Test"), it reads just fine. When I pass 4 as an argument in a variable, it fails.

As if this isn't weird enough, the library also has an example app which displays a menu from where you can view all the functionalities. Reading/writing strings from that app works. When I strip down that app to only read/write strings, it also fails. This while I have not touched that piece of the code.

    bool C24LCXX_I2C::Read(const short p_address, std::string & p_string, const bool p_readLengthFirst, const int p_length2write) {
        short address = p_address;    
        char i2cBuffer[2];
        i2cBuffer[0] = (unsigned char)(address >> 8);
        i2cBuffer[1] = (unsigned char)((unsigned char)address & 0xff);
        if (write(_slaveAddress, i2cBuffer, 2, true) == 0) {
            char buffer[p_length2write];
            int result = read(_slaveAddress, (char *)buffer, p_length2write);
            if (result == 0) {
                p_string.assign(buffer, p_length2write);        
                return true;
            }
        }
        return false;
    }

Is anyone able to shed some light on this?

25 Sep 2012

Hi,

Variable-length array definition implicitly generate malloc/free function call by mbed online compiler (ARM compiler 4.1). And your buffer[] will allocate in the heap memory rather than stack.

You can try to change a definition of your buffer[] as below:

char *buffer = (char *)alloca(p_length2write);

I am not sure this will fix a problem.

Regards,

25 Sep 2012

Hi,

Thanks for the advice but it didn't work. The program wil not run that line. No compiler error, but with debug statement before and after your line, only the statement before will output. When I replace the p_length2write with a hardcoded value, it does go on...