#include <math.h>
#include <iostream>
using namespace std;
int main()
{
const int p = 180, pi = 3.14;
int a, b, c, S;
float A, B, C;
cout « "vvedite b,c,S n";
cin » S » b » c;
A = pi - B - C; // C4700: используется 'B' и 'C'
b = a*sin(B)/sin(A); // C4700: используется 'a'
C = a*sin(C)/sin(A);
S = a*a*sin(B)*sin(C)/2*sin(A);
cout « "b=" « cos(b);
cout « "A=" « cos(A);
cout « "C=" « cos(C);
system("pause");
}
Выдаёт вот такие ошибки помогите пожалуйста
Не могу запустить рабочий проект под Visual Studio 2013 из-за этой ошибки. Проект старый, делался еще под Visual Studio 6.0. Видимо, там выдавалось предупреждение вместо ошибки.
Переменных много. Может быть, все-таки можно обойти эту ошибку, не инициализируя их все?
- visual-studio-2013
- visual-studio
- c++
Arhadthedev
11.4k8 золотых знаков42 серебряных знака69 бронзовых знаков
задан 2 фев 2015 в 21:10
nezzonezzo
1121 золотой знак2 серебряных знака8 бронзовых знаков
1 ответ
В свойствах проекта — свойства конфигурации — С/С++ — создание кода — проверка безопасности — Отключить проверку безопасности (/GS-)
ответ дан 2 фев 2015 в 21:34
nezzonezzo
1121 золотой знак2 серебряных знака8 бронзовых знаков
Я прочитал многие из предыдущих постов на C4700, но не могу найти решение своей проблемы.
У меня есть небольшой сценарий, написанный для демонстрации указателей структуры:
struct foo
{
int * bar;
};
#include<iostream>
using namespace std;
int main()
{
foo * fooptr;
int * num;
*num = 25;
*fooptr->bar = *num;
cout << "now fooptr points to a foo struct whose bar points to: " << *fooptr->bar;
fooptr->bar = num;
cout <<"now fooptr's struct's bar shares memory address with num at " <<num;
return 0;
}
Когда я его компилирую, я получаю два предупреждения C4700 о неинициализированных локальных переменных num и fooptr.
Я пошел дальше и инициализировал оба значения NULL, поэтому ошибка компилятора исчезла, но неудивительно, что я получил исключение:
Необработанное исключение в 0x00265DF7 в testing.exe: 0xC0000005: расположение записи нарушения прав доступа 0x00000000.
Вы видите, я всегда думал, что когда я не инициализирую эти указатели, они будут автоматически инициализироваться со случайными адресами (точно так же, как неинициализированным ints / chars / doubles будут назначаться garbages) — так не должно ли это быть здесь?
Если инициализация в этом случае действительно необходима (почему?), То есть ли легкий способ обойти эту проблему?
0
Решение
Неинициализированные переменные не инициализируются случайными значениями, они неинициализированы. На уровне машинного кода они имеют какое-либо значение при создании. Это может быть или не быть адрес реального объекта. В любом случае, это попытка получить доступ к значению неинициализированного указателя, как будто есть объект по этому адресу.
Итак, ваш компилятор делает вам одолжение, выдавая предупреждение (это не обязательно делать), потому что ваш код имеет неопределенное поведение.
тогда есть ли простой способ обойти эту проблему?
Установите указатели так, чтобы они указывали на действительные объекты, прежде чем разыменовывать их. Если вы этого не сделаете, то нет никаких обещаний о том, как будет вести себя ваша программа.
2
Другие решения
Вместо
int *num; // num points to somewhere random
*num = 25; // writing somewhere random makes zero sense
// and if your OS allowed you to do it, you would
// crash your computer very often.
ты должен написать
int num = 25;
int *pnum = # // pnum is a pointer to int which has been
// initialized with the address of num
И то же самое относится struct
содержание.
2
I have read through many of the previous posts on C4700, but I can’t seem to find a solution to my problem.
I have a little script written to demonstrate struct pointers:
struct foo
{
int * bar;
};
#include<iostream>
using namespace std;
int main()
{
foo * fooptr;
int * num;
*num = 25;
*fooptr->bar = *num;
cout << "now fooptr points to a foo struct whose bar points to: " << *fooptr->bar;
fooptr->bar = num;
cout <<"now fooptr's struct's bar shares memory address with num at " <<num;
return 0;
}
When I compile it, I get two C4700 warnings for uninitialized local variables num and fooptr used.
I went ahead and initialized both to NULL, so the compiler error went away but not surprisingly I got an exception:
Unhandled exception at 0x00265DF7 in testing.exe: 0xC0000005: Access violation writing location 0x00000000.
You see I always thought that when I don’t initialize those pointers, they’ll be automatically initialized with random addresses (just like uninitialized ints/chars/doubles will be assigned garbages)—so shouldn’t that be the case here?
If initialization in this case is indeed absolutely necessary (why?), then is there an easy workaround for this problem?
Перейти к контенту
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Warning (level 1 and level 4) C4700 |
Compiler Warning (level 1 and level 4) C4700 |
08/30/2022 |
C4700 |
C4700 |
2da0deb4-77dd-4b05-98d3-b78d74ac4ca7 |
uninitialized local variable ‘name‘ used
Remarks
The local variable name has been used, that is, read from, before it has been assigned a value. In C and C++, local variables aren’t initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.
To fix this issue, you can initialize local variables when they’re declared, or assign a value to them before they’re used. A function can be used to initialize a variable that’s passed as a reference parameter, or when its address is passed as a pointer parameter.
The /sdl
(Enable Additional Security Checks) compiler option elevates this warning to an error.
Example
This sample generates C4700 when variables t
, u
, and v
are used before they’re initialized, and shows the kind of garbage value that can result. Variables x
, y
, and z
don’t cause the warning, because they’re initialized before use:
// c4700.cpp // compile by using: cl /EHsc /W4 c4700.cpp #include <iostream> // function takes an int reference to initialize void initialize(int& i) { i = 21; } int main() { int s, t, u, v; // Danger, uninitialized variables s = t + u + v; // C4700: t, u, v used before initialization std::cout << "Value in s: " << s << std::endl; int w, x; // Danger, uninitialized variables initialize(x); // fix: call function to init x before use int y{10}; // fix: initialize y, z when declared int z{11}; // This C++11 syntax is recommended over int z = 11; w = x + y + z; // Okay, all values initialized before use std::cout << "Value in w: " << w << std::endl; }
When this code is run, t
, u
, and v
are uninitialized, and the output for s
is unpredictable:
Value in s: 37816963
Value in w: 42
Не могу запустить рабочий проект под Visual Studio 2013 из-за этой ошибки. Проект старый, делался еще под Visual Studio 6.0. Видимо, там выдавалось предупреждение вместо ошибки.
Переменных много. Может быть, все-таки можно обойти эту ошибку, не инициализируя их все?
Arhadthedev
11.4k8 золотых знаков39 серебряных знаков69 бронзовых знаков
задан 2 фев 2015 в 21:10
В свойствах проекта — свойства конфигурации — С/С++ — создание кода — проверка безопасности — Отключить проверку безопасности (/GS-)
ответ дан 2 фев 2015 в 21:34
nezzonezzo
1021 золотой знак2 серебряных знака8 бронзовых знаков
My issue is i am getting error C4700: uninitialized local variable ‘response’ used on line 26. I know it’s probably something simple I’m completely missing please help.
The local Driver’s License Office has asked you to write a program which grades the written portion of the driver’s license exam. The exam has 20 multiple choice questions. The correct answers are:
1. A 2. D 3. B 4. B 5. C 6. B 7. A 8. B 9. C 10. D 11. A 12. C 13. D 14. B 15. D 16. C 17. C 18. A 19. D 20. B
In main, declare an array and initialize it with the above correct answers. Also declare a second array for an exam taker’s answers, and get a text file name from the user.
1) have the user enter 20 answers from an exam taker and write the answers to the text file (validate that the answers are A, B, C, or D). See the 20 exam taker’s answers below.
Hint: open (and close) the file in the function.
2) read the text file of the exam taker’s answers and store them in the exam taker’s array, which was declared in main.
-a list of the numbers of the questions answered incorrectly (question numbers are 1-20).
Arrays must be processed using loops.
|
|