-1
 /* Note: The returned array must be malloced,
    assume caller calls free(). */
int* twoSum(int* nums, int numsSize, int target) {
    int *ans; //why error
    for(int i = 0; i < numsSize; i++){
        for(int j = i+1; j < numsSize; j++){
            if(nums[i] + nums[j] == target){
                ans[0] = i;
                ans[1] = j;
                break;
            }
        }
    }
    return ans;
}

Why code above is incorrect and code below correct (with malloc added)?

 /* Note: The returned array must be malloced,
    assume caller calls free(). */
int* twoSum(int* nums, int numsSize, int target) {
    int *ans = (int*)malloc(2*sizeof(int)); //why not error
    for(int i = 0; i < numsSize; i++){
        for(int j = i+1; j < numsSize; j++){
            if(nums[i] + nums[j] == target){
                ans[0] = i;
                ans[1] = j;
                break;
            }
        }
    }
    return ans;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Suprit_young
  • 21
  • 1
  • 4

1 Answers1

5

If you don't assign anything to ans, it contains some garbage value. Attempting to dereference the pointer (i.e. access what the pointer points to), which using an array index is implicitly doing, means you're trying to read/write some arbitrary memory location you're not supposed to.

Trying to use an invalid pointer invokes undefined behavior. This means your program may crash, it may output strange results, or it may appear to work properly. Also, making a seemingly unrelated change such as an extra call to printf for debugging, adding an unused variable, or compiling with different optimization settings can change how undefined behavior manifests itself.

So just because the program seems to be behaving properly doesn't mean there isn't a problem. It just means it will probably show up later when you least expect it.

A pointer needs to point to some valid memory location before you can use it. Calling malloc allocates a block of memory and returns a pointer to that memory. After assigning that address to ans, you can then use it to read/write the memory that was allocated. This guarantees that your program will be well defined.

dbush
  • 205,898
  • 23
  • 218
  • 273