user1745184
user1745184

Reputation: 103

C unknown access violation at first index in array

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.

Upvotes: 0

Views: 238

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76426

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

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25695

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.

Upvotes: 0

Related Questions