Why does memcpy change the last element of original array? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I encountered a weird bug in this code:
int *a = (int*) malloc(N*sizeof(int)); // allocate array
int i;
for (i=2; i<=N; i++)
{
a[i] = i;
}
int *b = (int*) malloc(N*sizeof(int));
memcpy(b, a, N*sizeof(b));
If I were to print out array a, output = 2,3,...,19 0
Whereas the expected output should have been 2,3,...,19,20.
Copying the array onto b strangely affected the last element.

An array of N elements has valid indexes 0, 1, ..., N - 1. Your final loop round accesses a[N], which is out of bounds and has undefined behaviour.

Related

Why different behaviour of same code by different compilers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.

Loading an array with the squares of it's subscripts in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#define N 500
int subscriptSquares[N];
void loadArray(int nums[], int size)
{
for(int i = 0; i <= (size - 1); i++)
{
nums[i] = i * i;
printf("%i\n", nums[i]);
}
}
What I'm trying to do more specifically is load an array of size 500 with its subscript squares (so subscriptSquares = {0, 1, 4, 9, 16, 25, ...250000}). My problem is somewhere along the line the values are shortened. The last value in the array actually becomes 249001 instead of 250000 and so on so forth. I thought it had something to with the data type so I switched it to double but ended up with same values with the obvious annoyance of decimals. int subscriptSquares[N] is inside the main function. If you need more information let me know
In your code you have defined an array of size 500. It will contain indices from 0 to 499.
So, the last result of your calculation will be 499*499 = 249001.
If you want to get the result of 500*500 then you have to declare an array of 501 locations. The below code shows how.
#define N 501
int subscriptSquares[N];
void loadArray(int nums[], int size)
{
for(int i = 0; i <= (size - 1); i++)
{
nums[i] = i * i;
printf("%i\n", nums[i]);
}
}

Fill a array with numbers from 0-100 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to fill an array with integers 0-100.
Here's my code:
int main()
{
int a[100];
for(int i = 0; i < a; i++)
{
a[i] = i;
printf("\n%d\n", a[i]);
}
}
I get this error:
comparison between pointer and integer (int and int) over the for line.
I can't figure it out. Any thoughts?
The cancel condition in your for loop is wrong. i<a You are comparing an int i variable with the pointer a that points to the memory location of the array. You would need to calculate the length of the array:
for(int i=0; i<sizeof(a)/sizeof(int); i++) {
But you could have found this solution in this 9 year old answer
Yes you are comparing pointer with an integer. This is why the error.
for(size_t i=0; i<sizeof(a)/sizeof(a[0]); i++) {
is what you wanted it to be and can be done in C language. Remember that sizeof operator results in value in size_t.
If you are not aware what that sizeof is doing - it is basically total number of bytes that the array object has - divided by each element's size - resulting in number of elements.
In case you are thinking from where did that pointer come?
Note one thing here a is converted into pointer (array decaying)to the first element - so it is nothing other than a pointer to the first element.
This should work for you,
int main()
{
int a[100];
int n = sizeof(a) / sizeof(a[0]); //Get the size of the array
for(int i=0; i<n; i++) { // loop through each elements of the array
a[i] = i;
printf("\n%d\n", a[i]);
}
}

Dynamic Array of strings [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to create an array of strings but I keep getting an error.
Can you help me figure out what's wrong with this code?
int size;
scanf("%d",&size);
char** arr;
arr=(char**)malloc(sizeof(char*)*size);
You can simply use array of n number of pointers to char. Then use a loop to allocate space for those.
int n, size;
scanf("%d %d", &n, &size);
char *arr[n];
for( int i = 0; i < n; ++i ){
arr[i] = malloc( size * sizeof(char) );
}

Unhandled exception at 0x012219c4 in SW-Serial.exe [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i declare 2d dynamic array. when run program this error shown:
Unhandled exception at 0x012219c4 in SW-Serial.exe: 0xC0000005: Access violation writing location 0xabababab.
the part of my program that error occured:
double** SWArray;
SWArray = (double**) malloc(lenA*sizeof(double*));
for (int i = 0; i <= lenA; i++)
SWArray[i] = (double*) malloc(lenB*sizeof(double));
for(int i=0;i<=lenA;i++){
SWArray[0][i]=0;
}
for(int j=0;j<=lenB;j++){
SWArray[j][0]=0;
}
picture of this problem
Arrays start from 0 in C. Wherever you say i <= lenA it should be i < lenA. Same goes for j and lenB. Also, the second loop doesn't really make sense. Did you mean lenB instead of lenA ?
You have lenA And lenB mixed up. It should be:
SWArray[i][0] and SWArray[0][j] in your loops.
And you loops should use < not <=
Both the loops are indexing in the wrong dimension and also are accessing elements beyond the size for which memory is allocated. You should change i<= to i< in both the loops
The correct way should be:
for(int i=0;i<lenA;i++){
SWArray[i][0]=0;
}
for(int j=0;j<lenB;j++){
SWArray[0][j]=0;
}

Resources