c: issues when allocating 2d char array dynamically? -


i'm trying allocate 2d char array accessed ary[i][j], using code:

#define stringmaxlen 20  void do_alloc( char ***vals, int valscount ){     *vals = (char**) calloc( sizeof( char** ), valscount );     int = 0;     ( ; i<valscount; i++ )         *vals[i] = (char*) calloc( sizeof( char* ), stringmaxlen ); }  int main( ){     //......     char** ary;     do_alloc( &ary, 10 );     strcpy( ary[0], "test" );     //...... } 

unfortunately, causes overflow somewhere , program have bug in execution, got references here dynamic allocation: http://staff.science.nus.edu.sg/~phywjs/cz1102/lecture20/sld014.htm.

i know what's wrong here , how solve issue, thanks.

you got operator precedence wrong: *vals[i] evaluates *(vals[i]), not (*vals)[i]. see http://en.wikipedia.org/wiki/operators_in_c_and_c%2b%2b#operator_precedence details.

the fix change *vals[i] (*vals)[i].

also, allocation *vals[i] = (char*) calloc( sizeof( char* ), stringmaxlen ); wrong. allocates way memory because allocates space stringmaxlen pointers, need stringmaxlen characters.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -