Whenever I run the following code, and give input as long string it gets exited with the return value 3221226356
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i=0;
char c,*input;
input=(char *)malloc(sizeof(char));
if(input==NULL)
{
printf("Could not allocate memory");
exit(1);
}
printf("%d size",strlen(input));
printf("Enter the string: ");
while((c=getchar())!='\n')
{
realloc(input, (sizeof(char)));
input[i++]=c;
}
printf("%s",input);
}
asked Sep 23, 2014 at 5:53
1
The realloc
function returns a new pointer. It doesn’t change the pointer you pass to it.
That means after the first call to realloc
you probably start writing to unallocated memory, leading to undefined behavior.
Also note that your realloc
call only allocates one byte. You need to allocate the previous size plus one.
There’s also the problem of you calling strlen
on a pointer to uninitialized memory (of size one by the way), which also leads to undefined behavior.
And since you treat the memory you allocate as a string, you should also allocate space for the string terminator, so the very first allocation should be for two bytes.
Another couple of notes: sizeof(char)
is specified to always result in 1
. And in C don’t cast the result of malloc
(and family).
answered Sep 23, 2014 at 5:59
The exit code 0xC0000374
is the value returned when heap corruption is detected.
Where you are reallocating, you do not reallocate more values. You free 1 char worth of memory, and then allocate a new 1 char memory segment. This causes input[i++]
to access a region outside of the area you allocated.
answered Sep 23, 2014 at 5:57
1
A lot of problems with this code:
- You cast the result of
malloc
, which is unnecessary - You always reallocate only 1 byte with
realloc
, but even given that, you do not do anything withrealloc
‘s return value (which is a resized pointer), so nothing useful happens here - Since you always have a 1-byte allocation to
input
, you attempt to access memory outside this allocation, which is going to return garbage (if you’re lucky enough not to get a seg fault)
Read up on documentation for malloc
and realloc
to figure out where your code is going wrong.
answered Sep 23, 2014 at 5:59
Alex ReynoldsAlex Reynolds
96.1k54 gold badges242 silver badges346 bronze badges
🐛 bug report
When building a relatively simple TypeScript file, it will build some of the time, but not others. For example, given the following TS file:
const config = { serverPort: 3000, }; export default config;
It will semi-randomly throw the error code 3221226356
🎛 Configuration (.babelrc, package.json, cli command)
{ "name": "@streampods/internalconfig", "description": "For internal use only. To share simple values between internal apps", "version": "0.0.0", "private": true, "source": "index.ts", "main": "dist/main.js", "module": "dist/module.js", "types": "dist/types.d.ts", "scripts": { "build": "parcel build" }, "devDependencies": { "@parcel/packager-ts": "^2.2.1", "@parcel/transformer-typescript-types": "^2.2.1", "parcel": "^2.2.1", "typescript": "^4.5.4" } }
🤔 Expected Behavior
No error should be thrown
😯 Current Behavior
When running build repeatedly, I get different results, but most of the time results in an exit code
🌈 git repro config main ≢ +6 | ~1 -1
↳ yarn build
yarn run v1.22.17
$ parcel build
√ Built in 480ms
dist\main.js 557 B 142ms
dist\module.js 239 B 113ms
dist\types.d.ts 115 B 24ms
Done in 1.01s.
🌈 git repro config main ≢ +6 | ~1 -1
↳ yarn build
yarn run v1.22.17
$ parcel build
√ Built in 469ms
error Command failed with exit code 3221226356.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
🌈 git repro config main ≢ +6 | ~1 -1
↳ yarn build
yarn run v1.22.17
$ parcel build
√ Built in 464ms
dist\main.js 557 B 142ms
dist\module.js 239 B 113ms
dist\types.d.ts 115 B 24ms
error Command failed with exit code 3221226356.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
💁 Possible Solution
Unfortunately, I have no idea what might be causing this problem.
🔦 Context
I’m trying to use parcel
to build a internal dependency in a TurboRepo monorepo for usage in both NodeJS (CJS) and Browser (ESM) applications
💻 Code Sample
Minimal reproduction lives here:
https://github.com/oceanbit/parcel-3221226356-repro
🌍 Your Environment
Software | Version(s) |
---|---|
Parcel | 2.2.1 |
Node | 16.13.1 |
npm/Yarn | 1.22.17 |
Operating System | Windows 11 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
int search(int *arr, int begin, int end, int key) // analog funkcii naxojdenia. Kak argument prinimayet int massiv { int t, res; res = -1; for(t = begin; t < end; t++) { if(arr[t] == -1) return -1; if(arr[t] == key) { res = t; break; } } return res; } void push_back(int **M, int M_size, int **N, int N_size) // adds array N to back of array M { int i; *M = (int*) realloc(*M, (M_size+N_size) * sizeof(int)); for(i = 0; i < N_size; i++) { *(*M + M_size + i) = *(*N + i); } return; } void dfs(char *table, int t_heig, int t_wid, int column, int *result, int *arr) { int i, k, old_size; if(column < 0) return; if(column >= t_wid) { // printf("inserting result to result-table\n"); // printf("value result[0] changed from %d to %d\n", result[0], result[0] + ((int)arr[0]+1)); // printf("sizeofresult: %d\n", result[0]); // printf("memory reallocated\n"); // printf("value result[%d] changed from %d to %d\n", result[0] - arr[0], result[result[0] - arr[0]], arr[0]); push_back(&result, result[0]+1, &arr, arr[0]+1); // +1, potomu chto 0-element massiva xranit kolvo elementov posle nego // printf("value result[0] changed from %d to %d\n", result[0], result[0] + (arr[0]+1)); result[0] = result[0] + arr[0] + 1; // printf("all elements of arr copied to result\n"); return; } printf("column: %d\n", column); for(i = 0; i < t_heig; i++) { if(table[i*t_wid + column] == 1) { if(search(arr, 1, arr[0]+1, i) == -1) { printf("step: %d; column: %d\n", i, column); old_size = arr[0]; arr[0] += 1; arr = (int*)realloc(arr, sizeof(int) * (arr[0] + 1)); // +1 potomu chto 0-element xranit dlinu massiva arr[arr[0]] = i; dfs(table, t_heig, t_wid, column+1, result, arr); arr[0] = old_size; } else { printf("Jump on step: %d; column: %d\n", i, column); dfs(table, t_heig, t_wid, column+1, result, arr); printf("returned on step: %d; column: %d\n", i, column); } } } return; } void perebor(char *table, int t_heig, int t_wid, int *result) { int *arr; /* массив для хранения результатов одного прохода рекурсии Этот массив будет скопирован как строку в "таблицу" result*/ result = (int*)realloc(result, sizeof(int)); result[0] = 0; /* размер первой строки "таблицы" результатов. Далее первая ячейка строки будет хранить размер строки. Это мне показалось удобным при работе с ней*/ arr = (int*)malloc(sizeof(int)); arr[0] = 0; // тоже хранит размер массива dfs(table, t_heig, t_wid, 0, result, arr); return; } |
I am making a snake game in console, but whenever I write system(«cls») in draw function it writes «Process exited with return value 3221226356» on Output screen.
I think there is some memory leak but I couldn’t find the exact reason why this is happening.
You can also see this code at: https://github.com/Lakshay-Dhingra/Snake-Game
Here’s my code: //Compiled in Dev-C++(Windows) with mingw std-c++11 compiler
#include<iostream>
#include<conio.h>
#include <unistd.h>
#include<cstdlib>
using namespace std;
class Node
{
int x;
int y;
Node *link;
public:
Node(int ix,int iy)
{
x=ix;
y=iy;
link=nullptr;
}
int getx()
{
return x;
}
void setx(int x)
{
this->x=x;
}
int gety()
{
return y;
}
void sety(int y)
{
this->y=y;
}
Node* getLink()
{
return link;
}
void setLink(Node* x)
{
link=x;
}
};
class LL
{
public:
Node* head;
LL()
{
head=nullptr;
}
void insert(int x,int y)
{
Node* mynode=new Node(x,y);
Node* temp=head;
head=mynode;
head->setLink(temp);
}
int* show(int l)
{
int* arr=new int(2*l);
int i=0;
Node* cur=head;
while(cur!=nullptr)
{
arr[i]=cur->getx();
arr[i+1]=cur->gety();
i+=2;
cur=cur->getLink();
}
return arr;
}
~LL()
{
Node* temp=head;
while(head!=nullptr)
{
temp=head->getLink();
delete head;
head=temp;
}
}
};
class Snake
{
int length;
LL* mysnake;
public:
Snake(int l,int x,int y)
{
mysnake=new LL();
for(int i=0;i<l;i++)
{
mysnake->insert((x+i),y);
}
length=l;
}
int getLength()
{
return length;
}
void eatFood(int x,int y)
{
length+=1;
mysnake->insert(x,y);
}
int* showSnake()
{
return mysnake->show(length);
}
int getHeadX()
{
return mysnake->head->getx();
}
int getHeadY()
{
return mysnake->head->gety();
}
};
class Window
{
int length;
int hieght;
Snake* snk;
int* arr;
public:
Window(int l,int h,int posx,int posy)
{
length=l;
hieght=h;
snk=new Snake(4,posx-3,posy);
arr=snk->showSnake();
}
void rungame()
{
char ch;
while(true)
{
if(kbhit())
{
ch = _getch();
if(int(ch)==27)
break;
}
draw();
}
}
void draw()
{
system("cls");
bool flag;
for(int i=0;i<length;i++)
{
for(int j=0;j<hieght;j++)
{
flag=0;
if(i==0||i==length-1||j==0||j==hieght-1)
{
cout<<"#";
flag=1;
}
else
{
for(int k=0;k<snk->getLength();k++)
{
if(i==arr[2*k]&&j==arr[2*k+1])
{
cout<<"O";
flag=1;
}
}
}
if(flag==0)
{
cout<<" ";
}
}
cout<<endl;
}
usleep(100000);
}
};
int main()
{
Window win(30,50,15,25);
win.rungame();
return 0;
}
Issue:
int* show(int l)
{
int* arr=new int(2*l);
// Above line was causing the issue
// It was a small silly mistake where I used round brackets
// instead of square brackets
// My program was treating arr as array which was causing memory leak
The CGO module gorfc provides GO bindings to pre-compiled SAP NWRFC SDK binaries. The module works fine on Linux and macOS and never worked quite stable on Windows. Currently, it occasionally terminates on Windows, with heap corruption error 3221226356 (hex C0000374).
I am not sure if the toolchain and compiler flags are maybe part of the problem, here further details.
Toolchain
SAP NWRFC SDK binaries require Microsoft C Runtime DLLs version 12.0 and our Windows toolchain is based on MinGW64, with following settings:
Version: 8.1.0 Architecture: x86_64 Threads: win32 Exception: seh Build revision: 0
The TDM GCC is not used because this issue still occurs: error adding symbols: File in wrong format
Is this the optimal toolchain for building CGO modules on Windows, or another approach could be considered?
Compiler flags
Compiler flags recommended for SAP NWRFC SDK bindings on Windows platform, are given for Windows native compiler and linker:
cl.exe -DSAPonNT -D_CRT_NON_CONFORMING_SWPRINTFS -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -D_AFXDLL -DWIN32 -D_WIN32_WINNT=0x0502 -DWIN64 -D_AMD64_ -DNDEBUG -DSAPwithUNICODE -DUNICODE -D_UNICODE -DSAPwithTHREADS -Inwrfcsdk/include -EHs -Gy -J -MD -nologo -W3 -Z7 -D_ATL_ALLOW_CHAR_UNSIGNED -GL -O2 -Oy- /we4552 /we4700 /we4789 -c -FosflightClient.obj sflightClient.c link.exe -OUT:sflightClient.exe -PDB:sflightClient.pdb -NXCOMPAT -STACK:0x2000000 -SWAPRUN:NET -DEBUG -OPT:REF -DEBUGTYPE:CV,FIXUP -MACHINE:amd64 -nologo -LTCG ole32.lib oleaut32.lib uuid.lib kernel32.lib advapi32.lib user32.lib gdi32.lib winspool.lib ws2_32.lib comdlg32.lib shell32.lib sflightClient.obj nwrfcsdk/lib/sapnwrfc.lib nwrfcsdk/lib/libsapucum.lib
GCC counterparts are currently missing for some of them, commented in gorfc source)
Any help/ideas on toolchain, flags, possible root causes and troubleshooting approach, would be of a great help.
Here the details about GO environment on Windows.
PS C:srcGOsrcgithub.comsapgorfc>go version go version go1.14 windows/amd64 PS C:srcGOsrcgithub.comsapgorfc> go env set GO111MODULE= set GOARCH=amd64 set GOBIN= set GOCACHE=C:Usersd037732AppDataLocalgo-build set GOENV=C:Usersd037732AppDataRoaminggoenv set GOEXE=.exe set GOFLAGS= set GOHOSTARCH=amd64 set GOHOSTOS=windows set GOINSECURE= set GONOPROXY= set GONOSUMDB= set GOOS=windows set GOPATH=c:srcGO set GOPRIVATE= set GOPROXY=https://proxy.golang.org,direct set GOROOT=C:ToolsGOLANG set GOSUMDB=sum.golang.org set GOTMPDIR= set GOTOOLDIR=C:ToolsGOLANGpkgtoolwindows_amd64 set GCCGO=gccgo set AR=ar set CC=gcc set CXX=g++ set CGO_ENABLED=1 set GOMOD=C:srcGOsrcgithub.comsapgorfcgo.mod set CGO_CFLAGS=-g -O2 set CGO_CPPFLAGS= set CGO_CXXFLAGS=-g -O2 set CGO_FFLAGS=-g -O2 set CGO_LDFLAGS=-g -O2 set PKG_CONFIG=pkg-config set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:Usersd037732AppDataLocalTempgo-build050373882=/tmp/go-build -gno-record-gcc-switches
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
int search(int *arr, int begin, int end, int key) // analog funkcii naxojdenia. Kak argument prinimayet int massiv { int t, res; res = -1; for(t = begin; t < end; t++) { if(arr[t] == -1) return -1; if(arr[t] == key) { res = t; break; } } return res; } void push_back(int **M, int M_size, int **N, int N_size) // adds array N to back of array M { int i; *M = (int*) realloc(*M, (M_size+N_size) * sizeof(int)); for(i = 0; i < N_size; i++) { *(*M + M_size + i) = *(*N + i); } return; } void dfs(char *table, int t_heig, int t_wid, int column, int *result, int *arr) { int i, k, old_size; if(column < 0) return; if(column >= t_wid) { // printf("inserting result to result-tablen"); // printf("value result[0] changed from %d to %dn", result[0], result[0] + ((int)arr[0]+1)); // printf("sizeofresult: %dn", result[0]); // printf("memory reallocatedn"); // printf("value result[%d] changed from %d to %dn", result[0] - arr[0], result[result[0] - arr[0]], arr[0]); push_back(&result, result[0]+1, &arr, arr[0]+1); // +1, potomu chto 0-element massiva xranit kolvo elementov posle nego // printf("value result[0] changed from %d to %dn", result[0], result[0] + (arr[0]+1)); result[0] = result[0] + arr[0] + 1; // printf("all elements of arr copied to resultn"); return; } printf("column: %dn", column); for(i = 0; i < t_heig; i++) { if(table[i*t_wid + column] == 1) { if(search(arr, 1, arr[0]+1, i) == -1) { printf("step: %d; column: %dn", i, column); old_size = arr[0]; arr[0] += 1; arr = (int*)realloc(arr, sizeof(int) * (arr[0] + 1)); // +1 potomu chto 0-element xranit dlinu massiva arr[arr[0]] = i; dfs(table, t_heig, t_wid, column+1, result, arr); arr[0] = old_size; } else { printf("Jump on step: %d; column: %dn", i, column); dfs(table, t_heig, t_wid, column+1, result, arr); printf("returned on step: %d; column: %dn", i, column); } } } return; } void perebor(char *table, int t_heig, int t_wid, int *result) { int *arr; /* массив для хранения результатов одного прохода рекурсии Этот массив будет скопирован как строку в "таблицу" result*/ result = (int*)realloc(result, sizeof(int)); result[0] = 0; /* размер первой строки "таблицы" результатов. Далее первая ячейка строки будет хранить размер строки. Это мне показалось удобным при работе с ней*/ arr = (int*)malloc(sizeof(int)); arr[0] = 0; // тоже хранит размер массива dfs(table, t_heig, t_wid, 0, result, arr); return; } |
See more:
I am compiling one sample code. But I am getting the answer when I am compiling that code for input = 5, If I change input from 5 to 6., then once answer came, but next time for same input, throwing a message «return value 3221226356». If again I change the input from 6 to 8, then again that message is coming.
#include <iostream> #include <string> #include <cmath> void loop1(float *a, int &k ) { int i = k / 2 ; for (int x = 0 ; x < i ; x++ ) { a[x] = x ; std::cout<<"a = "<< a[x] <<'n' ; } } void loop2(float *a, int &i, int &j ) { for (int x = i ; x < j ; x++ ) { a[x] = a[x-i] ; std::cout<<"a ["<<x<<"]= "<< a[x] <<'n' ; } } void loop3(float *a, int &i) { for (int x = 0 ; x < i ; x++ ) { a[x] = x * x * x ; a[x] += a[x]; } } int main() { int nx ; float* xpos = NULL; xpos = new float[nx]; std::cout<<"enter the value for nx " ; std::cin>>nx ; int a = nx/2 ; std::cout<<"a (= nx/2 )= "<< a <<'n' ; loop1(xpos, nx ); loop2(xpos, a, nx); for (int x = 0 ; x < nx ; x++ ) { std::cout<<"xpos = "<< xpos[x] <<'n' ; } for (int x = 0 ; x < nx ; x++ ) { std::cout<<"new xpos = "<< xpos[x] <<'n' ; } return 0 ; }
Result for Input = 5
enter the value for nx 5 a (= nx/2 )= 2 a = 0 a = 1 a [2]= 0 a [3]= 1 a [4]= 0 xpos = 0 xpos = 1 xpos = 0 xpos = 1 xpos = 0 new xpos = 0 new xpos = 1 new xpos = 0 new xpos = 1 new xpos = 0 -------------------------------- Process exited after 4.442 seconds with return value 0 Press any key to continue . . .
Result for Input = 6
enter the value for nx 6 a (= nx/2 )= 3 a = 0 a = 1 a = 2 a [3]= 0 a [4]= 1 a [5]= 2 xpos = 0 xpos = 1 xpos = 2 xpos = 0 xpos = 1 xpos = 2 new xpos = 0 new xpos = 1 new xpos = 2 new xpos = 0 new xpos = 1 new xpos = 2 -------------------------------- Process exited after 3.427 seconds with return value 0 Press any key to continue . . .
Result for Input = 8
<pre lang="c++">enter the value for nx 8 a (= nx/2 )= 4 a = 0 a = 1 a = 2 a = 3 a [4]= 0 a [5]= 1 a [6]= -------------------------------- Process exited after 7.167 seconds with return value 3221226356 Press any key to continue . . .
Have you got any idea about what I did wrong ?
Is there any specific name of such error?
But, I can’t find why that failed.
What I have tried:
I tried to vary the Input from one to other. But giving the message.
Updated 13-Nov-18 22:53pm
int nx ; float* xpos = NULL; xpos = new float[nx];
You have not set a value for nx, so your array may be any size between -2,147,483,647 and +2,147,483,647.
And remove those backslashes everywhere, what do you think they are for?
Look at your code:
int main() { int nx ; float* xpos = NULL; xpos = new float[nx];
How many floats are allocated in the array? Since you don’t set a value for nx
it will (if you are lucky, it depends on the compiler and the settings you gave it) default to zero.
And since it’s a local variable, the array is on the stack. When you use it, you access parts of the stack that aren’t a part of your array at all, and you corrupt them when you write to the array. At that point, anything can happen!
Allocate some suitable size to the array, or allocate the array once you know how many elements it needs to have!
To fix the obvious in your code
#include <iostream> void loop1(float a[], size_t k ) { size_t limit = k / 2 ; for (size_t x = 0 ; x < limit ; x++ ) { a[x] = x ; std::cout << "a = " << a[x] << 'n' ; } } void loop2(float a[], size_t i, size_t j ) { for (size_t x = i ; x < j ; x++ ) { a[x] = a[x-i] ; std::cout<<"a ["<<x<<"]= "<< a[x] <<'n' ; } } void loop3(float a[], size_t i) { for (size_t x = 0 ; x < i ; x++ ) { a[x] = x * x * x ; a[x] += a[x]; } } int main() { int nx ; float* xpos = NULL; std::cout<<"enter the value for nx " ; std::cin>>nx ; xpos = new float[nx]; int a = nx/2 ; std::cout<<"a (= nx/2 )= "<< a <<'n' ; loop1(xpos, nx ); loop2(xpos, a, nx); for (int x = 0 ; x < nx ; x++ ) { std::cout<<"xpos = "<< xpos[x] <<'n' ; } for (int x = 0 ; x < nx ; x++ ) { std::cout<<"new xpos = "<< xpos[x] <<'n' ; } delete [] xpos; }
You should give meaningful names to your functions.
You could use std::vector
instead of dynamically allocate yourself the array.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
#c #gcc #malloc #free
#c #gcc #malloc #Бесплатно
Вопрос:
Я изучаю C и решаю некоторые проблемы с кодированием.
При выполнении 1 задачи мне нужно создать динамический 2D-массив символов.
Я пытаюсь следовать некоторым другим ответам StackOverflow, чтобы динамически создавать 2D-массив.
Я могу создать его, но при попытке освободить память я получаю сообщение об ошибке 3221226356.
Ниже приведен мой код:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
scanf("%d", amp;n);
char **s = malloc(n * sizeof(char *));
for (int i = 0; i < n; i )
{
s[i] = malloc(1000 * sizeof(char));
//memset(s[i], '', 1000);
scanf("%s", amp;s[i]);
}
for (int i = 0; i < n; i )
{
printf("%s - %dn", amp;s[i], strlen(amp;s[i]));
}
for (int i = 0; i < n; i )
{
printf("Freeing %dn", i);
//char *tmp = amp;s[i];
free(s[i]);
}
printf("Freeing sn");
free(s);
if (argc > 1)
{
char xx[100];
scanf("%s", xx);
}
return EXIT_SUCCESS;
}
И пример запуска кода с выводом:
2
xx
sss
xx - 2
sss - 3
Freeing 0
[process exited with code 3221226356]
Я пытался вызвать free на amp;s[i], а также *s[i], но оба приводят к ошибке.
Мой компилятор — GCC.
Что я делаю не так?
Комментарии:
1. Ваши
malloc
free
вызовы and выглядят нормально, но вы искажаете указатели на строки,scanf
вводяamp;s[i]
вместоs[i]
. (%s
Формат и его двоюродный%[
брат принимают для заполнения строки, которые уже переданы как указатели. Также: пожалуйста, активируйте предупреждения с-Wall
помощью . Они покажут вам несоответствия формата.)2. Все ваши
amp;s[i]
должны быть простоs[i]
.amp;s[i]
имеет типchar **
, поэтому не может использоваться сscanf
,printf
,s[i]
и т.д. имеет типchar *
, который вам нужен. Ваш компилятор должен был предупредить об этих ошибках. На практике указатели будут иметь одинаковое значение, так что это будет «работать», но это неправильно.3. М. Оем прав, хотя, если вы хотите сохранить свою строку с определенным индексом , вы могли бы использовать
scanf('%s",amp;s[i][index]
,scanf("%s",s[i])
равнозначноscanf("%s",amp;s[i][0]
.4. Примечание: 3221226356 равно 0xC000 0374.
5. Лучший первый шаг — включить; все предупреждения компилятора. Хороший компилятор предупредит
scanf("%s", amp;s[i]); ... printf("%s - %dn", amp;s[i], strlen(amp;s[i]));
и ускорит ваше программирование.
Ответ №1:
Итак, отзывы о amp; s [i] привели меня к своего рода очевидному решению.
Чтобы создать временную переменную для scanf.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
scanf("%d", amp;n);
char **s = malloc(n * sizeof(char *));
for (int i = 0; i < n; i )
{
//s[i] = malloc(1000 * sizeof(char));
char *tmp = malloc(sizeof(char));
//memset(s[i], '', 1000);
scanf("%s", tmp);
s[i] = tmp;
}
for (int i = 0; i < n; i )
{
printf("%s - %dn", s[i], strlen(s[i]));
}
for (int i = 0; i < n; i )
{
printf("Freeing %dn", i);
//char *tmp = amp;s[i];
free(s[i]);
}
printf("Freeing sn");
free(s);
if (argc > 1)
{
char xx[100];
scanf("%s", xx);
}
return EXIT_SUCCESS;
}
Я начал писать простой класс для работы с матрицами, один конструктор заполняет матрицу одним числом, а другой принимает в качестве аргумента 2d массив.
#include <iostream>
using namespace std;
int i,j;
class Matrica
{
public:
Matrica(int, int, double);
Matrica(int, int, double*);
~Matrica();
void saberi(Matrica, Matrica);
void read();
void print();
private:
int n,m;
double* matrix;
};
Matrica::Matrica(int a, int b, double broj)
{
n = a;
m = b;
matrix = new double[n*m];
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
matrix[i*n + j] = broj;
}
}
}
Matrica::Matrica(int a, int b, double* matr)
{
n = a;
m = b;
matrix = new double[n*m];
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
matrix[i*n + j] = matr[i*n +j];
}
}
}
Matrica::~Matrica() {
delete[] matrix;
}
void Matrica::read() {
double e;
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout<< "insert element ["<<i<<"]["<<j<<"] :" <<endl;
cin >> e;
matrix[n*i +j] = e;
cout<< endl;
}
}
}
void Matrica::print() {
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout << matrix[n*i + j] << " ";
}
cout << endl;
}
}
void Matrica::saberi(Matrica A, Matrica B) {
cout << "foo";
}
int main()
{
Matrica A(3,3,1);
double K[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
Matrica B(3,3,&K[0][0]);
Matrica C(3,3,7);
C.saberi(A,B);
return 0;
}
Моя программа работала нормально, прежде чем я добавил пустой метод «saberi», который принимает два объекта в качестве аргументов. Если я это называю, моя программа падает с возвращаемым значением 3221226356. Что может быть не так? Заранее спасибо.
1
Решение
Как вы определили свою функцию подписи
void saberi(Matrica, Matrica);
Matrica
объекты передаются по значению, но вы не предоставили правильный конструктор копирования для класса Matrica
,
Самый простой способ решить вашу текущую проблему, это передать параметры по ссылке
void saberi(Matrica&, Matrica&);
или же
void saberi(const Matrica&, const Matrica&);
Во всяком случае, в долгосрочной перспективе вы должны либо предоставить правильный конструктор копирования
Matrica(const Matrica&);
или Fobid его (просто поместите объявление в private
секция класса).
1
Другие решения
Я делаю змеиную игру в консоли, но всякий раз, когда я пишу system («cls») в функции рисования, она пишет «Процесс завершен с возвращаемым значением 3221226356» на экране вывода. Я думаю, что есть некоторая утечка памяти, но я не мог найти точную причину, почему это происходит.
Вы также можете увидеть этот код по адресу: https://github.com/Lakshay-Dhingra/Snake- Игра
Вот мой код: // Скомпилировано в Dev-C ++ (Windows) с компилятором mingw std-c ++ 11
#include<iostream>
#include<conio.h>
#include <unistd.h>
#include<cstdlib>
using namespace std;
class Node
{
int x;
int y;
Node *link;
public:
Node(int ix,int iy)
{
x=ix;
y=iy;
link=nullptr;
}
int getx()
{
return x;
}
void setx(int x)
{
this->x=x;
}
int gety()
{
return y;
}
void sety(int y)
{
this->y=y;
}
Node* getLink()
{
return link;
}
void setLink(Node* x)
{
link=x;
}
};
class LL
{
public:
Node* head;
LL()
{
head=nullptr;
}
void insert(int x,int y)
{
Node* mynode=new Node(x,y);
Node* temp=head;
head=mynode;
head->setLink(temp);
}
// For Debugging:
// void showList()
// {
// Node* cur=head;
// while(cur->getLink()!=nullptr)
// {
// cout<<cur->getx()<<" "<<cur->gety()<<" --> ";
// cur=cur->getLink();
// }
// cout<<cur->getx()<<" "<<cur->gety()<<endl;
// }
int* show(int l)
{
int* arr=new int(2*l);
int i=0;
Node* cur=head;
while(cur!=nullptr)
{
arr[i]=cur->getx();
arr[i+1]=cur->gety();
i+=2;
cur=cur->getLink();
}
return arr;
}
~LL()
{
Node* temp=head;
while(head!=nullptr)
{
temp=head->getLink();
delete head;
head=temp;
}
}
};
class Snake
{
int length;
LL* mysnake;
public:
Snake(int l,int x,int y)
{
mysnake=new LL();
for(int i=0;i<l;i++)
{
mysnake->insert((x+i),y);
}
length=l;
}
int getLength()
{
return length;
}
void eatFood(int x,int y)
{
length+=1;
mysnake->insert(x,y);
}
int* showSnake()
{
return mysnake->show(length);
}
int getHeadX()
{
return mysnake->head->getx();
}
int getHeadY()
{
return mysnake->head->gety();
}
};
class Window
{
int length;
int hieght;
Snake* snk;
int* arr;
public:
Window(int l,int h,int posx,int posy)
{
length=l;
hieght=h;
snk=new Snake(4,posx-3,posy);
arr=snk->showSnake();
// rungame();
// For Debugging:
// for(int i=0;i<2*(sk.getLength());i++)
// {
// cout<<arr[i]<<" ";
// }
}
void rungame()
{
char ch;
while(true)
{
if(kbhit())
{
ch = _getch();
if(int(ch)==27)
break;
}
draw();
}
}
void draw()
{
system("cls");
// arr=snk->showSnake();
// cout<<"world ";
bool flag;
for(int i=0;i<length;i++)
{
for(int j=0;j<hieght;j++)
{
flag=0;
if(i==0||i==length-1||j==0||j==hieght-1)
{
cout<<"#";
flag=1;
}
else
{
for(int k=0;k<snk->getLength();k++)
{
if(i==arr[2*k]&&j==arr[2*k+1])
{
cout<<"O";
flag=1;
}
}
}
if(flag==0)
{
cout<<" ";
}
}
cout<<endl;
}
// For Debugging:
// for(int k=0;k<snk->getLength();k++)
// cout<<arr[2*k]<<" "<<arr[2*k+1]<<" ";
usleep(100000);
}
};
int main()
{
Window win(30,50,15,25);
win.rungame();
return 0;
}
2 ответа
Лучший ответ
Ошибка 3221226356 — это 0xc0000374 в шестнадцатеричном формате, то есть STATUS_HEAP_CORRUPTION.
Я пропустил его при первом прочтении, но оно вызвано вашим выделением в show()
:
int* arr=new int(2*l);
Это выделяет пробелы для single int
и заполняет его значением 2*l
. Впоследствии вы пишете в нераспределенную / неинициализированную память: arr[1]
, arr[2]
и т. Д.
Немедленное исправление просто:
int* arr = new int[2*l];
Это выделяет пространство для 2*l
int
значений.
В долгосрочной перспективе вам лучше вместо этого использовать std::vector<int>
или отказаться от всей этой работы с массивами и обходить свой связанный список напрямую, когда вам нужно (например, в вашей функции draw
).
0
Botje
30 Янв 2020 в 09:57
unistd.h
— заголовок UNIX (Linux, MacOS и т. Д.), Его не следует включать в проект Windows. Это может быть причиной.
Вызов system("clear");
в Linux SO.
Затем вам нужно заменить функции, такие как usleep()
, которые принадлежат unistd.h
и не могут использоваться в проекте Windows.
Я считаю, что windows.h
имеет некоторые похожие функции.
1
anastaciu
30 Янв 2020 в 09:53
realloc
Функция возвращает новый указатель. Это не меняет указатель, который вы передаете ему.
Это означает, что после первого звонка realloc
вы, вероятно, начинаете писать в нераспределенную память, что приводит к неопределенному поведению.
Также обратите внимание, что ваш realloc
Вызов только выделяет один байт. Вам нужно выделить предыдущий размер плюс один.
Есть также проблема, когда ты звонишь strlen
указатель на неинициализированную память (кстати, первого размера), что также приводит к неопределенному поведению.
И так как вы рассматриваете память, которую вы выделяете как строку, вы также должны выделить место для ограничителя строки, поэтому самое первое выделение должно быть для двух байтов.
Еще пара замечаний: sizeof(char)
указано всегда приводить к 1
, И в C не приведите результат malloc
(и семья).