0

Below I have a method that constructs a permutated string of a given string (str). I don't really know why but sometimes while debugging I receive the following exception:

Unhandled exception at 0x01282665 in test.exe: 0xC0000005: Access violation 
writing     location 0x00000000.

when trying to assign ('u') at index 0 in ret_str (ret_str[l]=elem[0])

unsigned char* getPermStr(long length,unsigned char* strt,unsigned char* elem){
    unsigned char* ret_str;
    long l = 0;
    ret_str = (unsigned char*) calloc(length,sizeof(unsigned char));
    while(l < length){
        if(elem < (strt+length-1)){
            ret_str[l]=elem[0];  // ACCESS VIOLATION HERE
            elem+=1;
        }else{
            ret_str[l]=elem[0];
            elem = strt;
        }
        l+=1; 
    }
    return ret_str;
}

I don't see why the access violation occurs... I'm within the bounds of my ret_str so what is wrong? BTW: The string ret_str is free'd after the function call.

UPDATE: There was no problem with elem. The reason was that I allocated memory while there was no memory left on the heap for dynamic allocation (due of lots of memory leaks) so calloc returned a NULL pointer. That's why the error occured.

user1745184
  • 93
  • 1
  • 8

2 Answers2

1

You need to check whether elem is null. If it is null your function should return an error code.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • If not `NULL` `elem` most certainly points to memory not belonging to the process. – alk Oct 19 '12 at 16:58
  • There was no problem with elem. The reason was that I allocated memory while there was no memory left on the heap for dynamic allocation (due of lots of memory leaks) so calloc returned a NULL pointer. That's why the error occured. – user1745184 Oct 20 '12 at 15:25
0

ret_str = (unsigned char*) calloc(length,sizeof(unsigned char)); Change this line to

ret_str = malloc(length * sizeof(unsigned char));
if(ret_str == NULL){ return "" ;}
//--whatever
while(l < length){
        if(elem < (strt+length-1)){
            ret_str[l]=elem[0];  // ACCESS VIOLATION HERE
            elem+=1;
        }else{
            ret_str[l]=elem[0];
            elem = strt;
        }
        l+=1; 
    }

Also make sure, elem is accessible. Chances are, elem isn't initialised.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78