Ошибка c4703 c

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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
 
struct data{
    char fam[10];
    int m[3];
};
struct student{
    data d;
    student *next;
};
student *st = 0, *en = 0;
 
void view()
{   system("cls");
    if (!st){
        cout << "+------------------------------------------------+" << endl;
        cout << "|                   Ничего нет!                  |" << endl;
        cout << "+------------------------------------------------+" << endl;
        cin.get(); cin.get();
        return;
    }
    student *tmp = st; int i = 0;
    cout << "+------------------------------------------------+\n";
    cout << "|   |              |            Оценки           |\n";
    cout << "| № |   Фамилия    |-----------------------------|\n";
    cout << "|   |   студента   |Физика |История |Информатика |\n";
    cout << "+------------------------------------------------+\n";
    while (tmp)
    {
        printf("|%2d | %-12s |%6d |%7d |%11d |\n", ++i, tmp->d.fam, tmp->d.m[0], tmp->d.m[1], tmp->d.m[2]);
        tmp = tmp->next;
    }
    cout << "+------------------------------------------------+\n";
    cout << "Для выхода нажмите Enter" << endl;
    cin.get(); cin.get();
    return;
}
 
student scan(){
    student el;
    cout << "Фамилия: "; cin >> el.d.fam;
    if (el.d.fam[0] == '*') return el;
    cout << "Оценки (3): "; cin >> el.d.m[0] >> el.d.m[1] >> el.d.m[2];
    el.next = NULL;
    return el;
}
void addnew(student el)
{   if (el.d.fam[0] != '*')
    {
        if (!st) {
            st = new student;
            *st = el;
            st->next = NULL;
            en = st;
        }
        else
        {
            student *tmp, *tmp2, *tmp3;
            tmp = st;
            tmp3 = new student;
            *tmp3 = el;
            int flag = 0;
            while (strcmp(tmp->d.fam, (el.d.fam)) < 0)
            {
                tmp2 = tmp;
                tmp = tmp->next;
                flag = 1;
                if (!tmp) break;
            }
 
            if (!flag) { tmp3->next = tmp; st = tmp3; }
            else if (!tmp){ tmp2->next = tmp3; en = tmp3; }
            else{
                tmp2->next = tmp3;
                tmp3->next = tmp;
            }
        }
    }
}
 
void delall(){
    student *temp;
    if (st == NULL) return;
    while (1)
    {
        temp = st;
        st = st->next;
        delete temp;
        if (st == NULL) break;
    }
    en = NULL;
    cout << "Список очищен" << endl;
    cin.get(); cin.get();
    return;
}
 
void create(){
    student el;
    cout << "Для выхода нажмите * в поле фамилии" << endl;
    while (1)
    {   el = scan();
        if (el.d.fam[0] != '*') addnew(el);
        else break;
    }
    return;
}
void keysearch(){
    student *tmp;
    char n[10];
    int count = 0, found = 0;
    tmp = st;
    cout << "Введите фамилию для поиска" << endl;
    cin >> n;
    system("cls");
    cout << "+------------------------------------------------+" << endl;
    cout << "|                 Поиск элементов                | " << endl;
    cout << "+------------------------------------------------+\n";
    cout << "|   |              |            Оценки           |\n";
    cout << "| № |   Фамилия    |-----------------------------|\n";
    cout << "|   |   студента   |Физика |История |Информатика |\n";
    cout << "+------------------------------------------------+\n";
    while (tmp) {
        count++;
        if (strcmp(tmp->d.fam, n) == 0) {
            found = 1;
            printf("|%2d | %-12s |%6d |%7d |%11d |\n", count, tmp->d.fam, tmp->d.m[0], tmp->d.m[1], tmp->d.m[2]);
            cout << "+------------------------------------------------+" << endl;
        }
        tmp = tmp->next;
        }
    if (!found)
    {   cout << "|       Введенного элемента нет в списке         |" << endl;
        cout << "+------------------------------------------------+" << endl;
    }
    cin.get();  cin.get();
}
 
 
void deletet(){
    student *tmp, *tmp2;
    int n, i = 0, flag = 0;
    tmp = st;
    cout << "Введите номер удаляемого элемента" << endl;
    cin >> n;
    if (n == 1){ tmp2 = tmp->next; st = tmp2; delete tmp; }
    else
    {   while (tmp)
        {
            ++i;
            if (i == (n - 1))
            {   tmp2 = tmp->next;
                tmp->next = tmp->next->next;
                delete tmp2;
                flag = 1;
                break;
            }
            tmp = tmp->next;
        }
        if (flag) cout << "Элемент удален" << endl;
        else cout << "Нет элемента с таким номером" << endl;
        cin.get(); cin.get();
    }
}
 
int read() {
    int a, i = 0;
    student el;
    ifstream fin("1.txt", ios::binary | ios::in);
    if (!fin) return -1;
    else {
        cout << "Удалить существующие элементы? Да=1" << endl;
        cin >> a;
        if (a == 1) delall();
        fin.seekg(0, ios::beg);
        while (fin.read((char*)&(el.d), sizeof data))
        {   el.next = NULL;
            addnew(el);
            i++;
        }
    }
    fin.close();
    return i;
}
 
void save(){
    student *tmp = st;
    ofstream fout("1.txt", ios::out | ios::trunc);
    if (!fout)
    {   cout << "Не могу открыть файл для записи" << endl;
        cin.get(); cin.get(); return;
    }
    else
    {
        while (tmp)
        {   fout.write((char*)&tmp->d, sizeof data);
            tmp = tmp->next;
        }
        fout.close();
    }
    return;
}int main()
{
    setlocale(0, "rus");
    char c = 0;
    int i = -2;
 
    while (1){
        system("cls");
        cout << "+-------------------------------+" << endl;
        cout << "|     Коротков А.А. ПЗ №2       |" << endl;
        cout << "+-------------------------------+" << endl;
        if (i == -2) cout << "|         Статус файла          |" << endl;
        else
        if (i == -1) cout << "|     Не могу открыть файл      |" << endl;
        else cout << "|     Считано " << setw(3) << i << " записей       |" << endl;
 
        cout << "+-------------------------------+" << endl;
        cout << "|             Меню              |" << endl;
        cout << "+-------------------------------+" << endl;
        cout << "|1-Организация нового списка    |" << endl;
        cout << "|2-Добавление элемента          |" << endl;
        cout << "|3-Поиск элементата по фамилии  |" << endl;
        cout << "|4-Удаление элементата по номеру|" << endl;
        cout << "|5-Просмотр списка              |" << endl;
        cout << "|6-Очистка списка               |" << endl;
        cout << "|7-Сохранить в файл             |" << endl;
        cout << "|8-Считать из файла             |" << endl;
        cout << "|0-Выход                        |" << endl;
        cout << "+-------------------------------+\n";
        cin >> c;
        switch (c){
        case'1': create(); break;
        case'2': addnew(scan()); break;
        case'3': keysearch(); break;
        case'4': deletet(); break;
        case'5': view(); break;
        case'6': delall(); break;
        case'7': save(); break;
        case'8': i = read(); break;
        case'0': return 0; break;
        default: {cout << "Вводите числа 1-8" << endl; cin.get(); cin.get(); }
        }
    }
    return 0;
}

I’m working on a crypter project and ran into the following error when attempting to compile the program.

main.cpp(520): error C4703: potentially uninitialized local pointer
variable ‘pNamesPtr’ used
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        DLLNAMES[i].UsedAlready = 0;
    }


    *dwOutSize = (DWORD)pNamesPtr - (DWORD)pBuffer;//*<----is line 520 of error
    *dwImportsSize = *dwOutSize - *dwIATSize;    
    return pBuffer;
}
#pragma pack(1)
typedef struct

Can someone help me with this error? Do you need more code in order to have a good answer?

SSpoke's user avatar

SSpoke

5,65610 gold badges73 silver badges124 bronze badges

asked Feb 27, 2014 at 5:02

user3191413's user avatar

2

This warning isn’t always a bug, sometimes its just the result of an optimization. Since it is in your code and you don’t know what is this it might actually be a bug.

For example if I write:

int i;

if (this_and_that)
    i = 5;

if (whatever)
    printf("%d\n", i);  // <--- this may give a potential blahblah warning

If you are optimizing then you may know that the value of whatever is always true when the value of this_and_that is true so if printf gets called then i is already guaranteed to be initialized but the compiler often can not figure out the relation between this_and_that and whatever, this is why you get the warning. One possible quick fix to this warning is initializing the variable to a default value right where you declare it. In my opinion sparing with initialization is a bad practice and a source of a lot of bugs.

answered Feb 27, 2014 at 5:11

pasztorpisti's user avatar

pasztorpistipasztorpisti

3,7601 gold badge16 silver badges26 bronze badges

4

It means that

  • you don’t initialise pNamesPtr when you declare it, so it starts with an invalid value; and
  • the compiler can’t be sure that you will have assigned a valid value to it before using it.

Check all the code paths from the declaration to the point of use. Do they all assign something sensible to the variable? If not, fix it so they do.

If they do, and you’re convinced that you’re assigning it correctly, could you simplify the code so that it’s obvious to the compiler that it is?

If all else fails, then you could silence the compiler by initialising it to nullptr or some other default value in the initialisation. But only do that if you’re really sure your code is correct — compilers are usually good at spotting mistakes like this.

answered Feb 27, 2014 at 5:08

Mike Seymour's user avatar

Mike SeymourMike Seymour

250k28 gold badges450 silver badges645 bronze badges

This error mean that compier don’t know if used variable have assigned value.
For example:

int i;
if( someBool )
    i= 123;
someFunction();
if( someBool )
    printf("%d", i );

If someFunction() change value of someBool then you may end up calling printf with i argument while i doesn’t have any value assigned.

If you are sure that your code is correct you may disbale that error in Visual Studio by putting at the top of your cpp file line:

#pragma warning (disable: 4703)

Or you may disable that check for whole project by going to Properties / C/C++ / General / SDL checks and set it to No (/sdl-).

Alternatively if you don’t care about performance you may just assign anything to pNamesPtr where it’s defined.

answered Feb 26 at 15:12

LovelyHanibal's user avatar

Put this in your code:

xtype *pNamesPtr = NULL

Benjamin W.'s user avatar

Benjamin W.

46.3k19 gold badges108 silver badges117 bronze badges

answered Feb 15, 2016 at 8:55

chen zhiwei's user avatar

1

Я работаю над проектом crypter и при попытке скомпилировать программу столкнулся с следующей ошибкой.

main.cpp(520): ошибка C4703: потенциально неинициализированный локальный указатель переменная ‘pNamesPtr’ используется
========== Build: 0 удалось, 1 не удалось, 0 обновлено, 0 пропущено ==========

        DLLNAMES[i].UsedAlready = 0;
    }


    *dwOutSize = (DWORD)pNamesPtr - (DWORD)pBuffer;//*<----is line 520 of error
    *dwImportsSize = *dwOutSize - *dwIATSize;    
    return pBuffer;
}
#pragma pack(1)
typedef struct

Может кто-нибудь помочь мне с этой ошибкой? Вам нужен больше кода, чтобы иметь хороший ответ?

Поделиться

Источник

3 ответа

Это предупреждение не всегда является ошибкой, иногда просто результатом оптимизации. Так как это в вашем коде, и вы не знаете, что это такое, это может быть ошибка.

Например, если я пишу:

int i;

if (this_and_that)
    i = 5;

if (whatever)
    printf("%d\n", i);  // <--- this may give a potential blahblah warning

Если вы оптимизируете, вы можете знать, что значение whatever всегда истинно, если значение this_and_that истинно, поэтому, если printf вызывается, тогда i уже гарантированно инициализируется, но компилятор часто не может определить связь между this_and_that и whatever, поэтому вы получаете предупреждение. Одним из возможных быстрых исправлений для этого предупреждения является инициализация переменной до значения по умолчанию, где вы ее объявляете. На мой взгляд, избавление от инициализации — плохая практика и источник множества ошибок.

pasztorpisti

Поделиться

Это означает, что

  • вы не инициализируете pNamesPtr, когда вы его объявляете, поэтому он начинается с недопустимого значения; и
  • компилятор не может быть уверен, что перед его использованием вам будет присвоено действительное значение.

Проверьте все пути кода от объявления до точки использования. Все ли они назначают что-то разумное для переменной? Если нет, исправьте это, чтобы они это сделали.

Если они это сделают, и вы уверены, что правильно назначили его, можете ли вы упростить код, чтобы он был очевидным для компилятора?

Если все остальное не удается, вы можете отключить компилятор, инициализируя его значением nullptr или другим значением по умолчанию в инициализации. Но делайте это только в том случае, если вы действительно уверены, что ваш код верен — компиляторы обычно хорошо разбираются в таких ошибках.

Mike Seymour

Поделиться

Поместите это в свой код:

xtype *pNamesPtr = NULL

chen zhiwei

Поделиться

Ещё вопросы

  • 0$ обновить метод PUT в Angular?
  • 0Как я могу передать свой заводской результат другому контроллеру?
  • 1Автоматизация NonEnglish сайт, используя WebDriver
  • 0ЗАГРУЗКА ДАННЫХ INFILE с удаленного сервера при получении ошибки
  • 0ng Cordova file_uri к base64
  • 0Красивая ошибка декодирования супа
  • 1Установить кортеж в качестве имени столбца в Pandas
  • 0Почему мой URL-адрес angularjs отличается?
  • 0Показать / скрыть без использования CSS
  • 0Как обновить страницу и добавить параметр URL?
  • 1Панды сбрасываются перед первым действительным индексом и после последнего действительного индекса для каждого столбца кадра данных
  • 1отображение маршрута 404 при обновлении asp.net MVC 3 до MVC 5
  • 1Несколько синхронизированных функций в одном потоке
  • 0$ location в $ timeout в AngularJS
  • 1Как получить значения объекта, используя свойство идентификатора объекта в C #
  • 1Как показать ProgressBar через определенное время
  • 1Есть ли ярлык, чтобы повторить последнее сканирование StyleCop
  • 0Отладка без отладочных символов
  • 0G ++ с Mountain Lion поддерживает -msse4.2?
  • 1Запрос веб-службы не отображает строки в массиве
  • 0Сравните 2 массива с array_diff
  • 0Когда использовать & в C ++ при объявлении переменных?
  • 1Разобрать данные и представить изображение PNG
  • 0Вложенная функция C ++ с указателем в качестве возвращаемого значения
  • 1Нажмите на ссылку, используя селен вебдрайвер
  • 0sqlsrv драйвер для Windows PHP PDO SQL сервер
  • 0ngFlow — отправлять CSRF_token через угловой в laravel
  • 0Как передать значение из DropDownListFor в угловую функцию?
  • 0Извлечение JSON в транспортир и сравнение его с данными, отправленными из серверной части
  • 1RoutingMissingException с использованием NEST IndexMany <>
  • 0Как узнать, есть ли у элемента другой элемент внутри его класса
  • 0Файл как аргументы командной строки
  • 1Angular CLI использует SystemJS?
  • 1Обнаружение предварительного запуска Google Play в Unity
  • 0Значение переменной $ scope не обновляется в контроллере Angular JS?
  • 0двойной выход в Cout C ++
  • 0XAMPP PHP файл работает, но нет результата?
  • 1Шрифт C3.js tootltip
  • 0Как динамически загружать контент в приложения для Windows 8
  • 0Установите опцию по умолчанию в меню выбора, не сохраняя ее в модели
  • 0Неактивная пользовательская функция
  • 1Работают ли делегаты C # как функции Excel / User Defined?
  • 1Использование глобальных обработчиков исключений и локальных
  • 1Чтение из нескольких обменов RabbitMQ в клиенте Java не опрос
  • 0Smarty strpos и substr для получения текста после последней косой черты в URL
  • 1Вызовите функцию typed.js внутри компонента Vue
  • 1Как установить элементы заливки в BottomNavigationView на Android
  • 0JQuery обходится, чтобы добавить класс
  • 0Проблемы компиляции при наследовании от класса, вложенного в шаблон [duplicate]
  • 0Неправильные значения умножения матриц

Сообщество Overcoder

Member Avatar for lmuller89


Hi all,

I am coming accross a problem that says «C4703: potentially uninitialized local pointer variable ‘data_list’ used» and «C4703: potentially uninitialized local pointer variable ‘filter_list’ used». I have tried initilizing the pointer like I have read while googling it but have not managed to get it to work as even after trying to initialize it it still comes accross with an error.
This is my code that is giving me problems.
Thanks

void TheMenu::Load(TheFilter& Filter, TheData& Data)
{
    fstream input_file;

    input_file.open("task2_data.txt"); //open the file

    if (!input_file)
    {
        cout<<"\nFile does not exist" << endl;
        //exit(0);
    }
    else
    {/////////////////////////////////////////////////////////
        int data_count = -1;
        int data_size = -1;
        int filter_count = -1;
        int filter_size = -1;
        double* data_list;
        double* filter_list;


        while (!input_file.eof()) //while we haven't reached the end of the file
        {
            string str;
            getline(input_file,str); //get the current line in the file (separated by \n)  - get from input_file, store it in the string str

            if (data_count == -1) {// 1st time entering loop get size of data array.
                data_size = atoi(str.c_str());//convert string to integer
                //Data.SetData(new double[data_count]);
                data_list = new double[data_size];
            }

            if ((data_count != -1) && (data_count < data_size))
            {   
                double val = atof(str.c_str()); // string float, double type used in other classes
                data_list[data_count] = val; // data list @ position 

                if(data_count+1 == data_size)
                {
                    Data.SetData(data_list);
                    Data.SetLength(data_size);
                    Data.SetValid(true);
                    cout << "data loaded" <<endl;
                    filter_count = 0;   // info for next loop 
                    data_count = data_size; // match position to number of vales, if true begin saving to class 
                }
            }
            else if (filter_count != -1)
            {
                if (filter_size == -1) {
                    filter_size = atoi(str.c_str());
                    filter_list = new double[filter_size];
                    filter_count--;
                }

                else if ((filter_count != -1) && (filter_count < filter_size))
                {
                    double val = atof(str.c_str());
                    filter_list[filter_count] = val;

                    if(filter_count+1 == filter_size)
                    {
                        Filter.SetValues(filter_list);
                        Filter.SetLength(filter_size);
                        Filter.SetValid(true);
                        cout << "filter loaded" <<endl;
                    }
                }
                filter_count++;
            }

            data_count++;   
        }


    }
}


Recommended Answers

I think you can remove the warning by initializing those two pointers to NULL when they are declared on lines 18 and 19.

Jump to Post

All 3 Replies

Member Avatar for Ancient Dragon


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster



I think you can remove the warning by initializing those two pointers to NULL when they are declared on lines 18 and 19.

Edited

by Ancient Dragon

Member Avatar for rubberman


rubberman

1,355



Nearly a Posting Virtuoso



Featured Poster



Since this is C++, use 0 to initialze these variables. IE:

double* data_list = 0;
double* filter_list = 0;

Member Avatar for Lucaci Andrew


You only declared your pointer. Also you allocate memory for your filter_list pointer in an if clause, yet you try to access that pointer in an else if clause.

The compiler throws a warning, saying that it’s possible to enter only in the else if clause, without entering first in the if clause, thus getting in a situation where your pointer is not initialized, and you want to use it.

double* filter_list;
//...

if (filter_size == -1) {
    //...
    filter_list = new double[filter_size]; //allocation
    //...
}
else if ((filter_count != -1) && (filter_count < filter_size))
{
    //...
    filter_list[filter_count] = val; //using the variable
    //...
}

Edited

by Lucaci Andrew


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

On our addon for Kodi https://github.com/xbmc/audiodecoder.vgmstream becomes your vgmstream used.
In the build systems used for Windows UWP there, a warning is automatically declared as an error.

This change sets the variable to NULL there, which removes the warning.

Error:

d:\a\1\audiodecoder.vgmstream\lib\vgmstream\src\meta\csb.c(142): error C4703: potentially uninitialized local pointer variable 'stream_name' used [D:\a\1\s\build\audiodecoder.vgmstream-prefix\src\audiodecoder.vgmstream-build\lib\vgmstream\src\libvgmstream.vcxproj] [D:\a\1\s\build\audiodecoder.vgmstream.vcxproj]

Related build log:
https://dev.azure.com/teamkodi/binary-addons/_build/results?buildId=6134&view=logs&j=cc6cffab-e95c-563d-eef4-026ebc0684ec&t=4caacdc4-d3f5-50ea-479d-35158b55a00e&l=583

Понравилась статья? Поделить с друзьями:
  • Ошибка c46 suzuki gsx r 750
  • Ошибка c46 gsxr 600
  • Ошибка c4201 kyocera 2540
  • Ошибка c41568 форд мондео
  • Ошибка c40168 ford