Меню

Ошибка stray 302 in program

I have a problem compiling the following exploit code:

http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c

I am using «gcc file.c» and «gcc -O2 file.c», but both of them results in the following errors:

sorbolinux-exec.c: In function ‘sc’:
sorbolinux-exec.c:76: error: stray ‘302’ in program
sorbolinux-exec.c:76: error: stray ‘244’ in program
sorbolinux-exec.c:76: error: ‘t’ undeclared (first use in this function)
sorbolinux-exec.c:76: error: (Each undeclared identifier is reported only  once
sorbolinux-exec.c:76: error: for each function it appears in.)

I tried compiling them on both Kali Linux and Ubuntu 10.04 (Lucid Lynx) and got the same result.

Peter Mortensen's user avatar

asked Oct 5, 2013 at 13:15

Ahmed Taher's user avatar

8

You have an invalid character on that line. This is what I saw:

enter image description here

answered Oct 5, 2013 at 13:31

Yu Hao's user avatar

Yu HaoYu Hao

118k44 gold badges232 silver badges287 bronze badges

7

You have invalid characters in your source. If you don’t have any valid non-ASCII characters in your source, maybe in a double quoted string literal, you can simply convert your file back to ASCII with:

tr -cd '11121540-176' < old.c > new.c

The method with iconv will stop at wrong characters which makes no sense. The above command line is working with the example file.

Peter Mortensen's user avatar

answered Oct 5, 2013 at 13:45

Klaus's user avatar

KlausKlaus

23.7k6 gold badges56 silver badges109 bronze badges

0

Sure, convert the file to ASCII and blast all Unicode characters away.
It will probably work… But…

  1. You won’t know what you fixed.
  2. It will also destroy any Unicode comments. Example: //: A²+B²=C²
  3. It could potentially damage obvious logic and the code will still be broken,
    but the solution less obvious.
    For example: A string with «Smart-Quotes» (“ & ”) or a pointer with a full-width asterisk (*). Now “SOME_THING” looks like a #define (SOME_THING) and *SomeType is the wrong type (SomeType).

Two more surgical approaches to fixing the problem:

  1. Switch fonts to see the character. (It might be invisible in your current font)

  2. Regular expression search all Unicode characters not part of non-extended ASCII.

    In Notepad++ I can search up to FFFF, which hasn’t failed me yet.

    [x{80}-x{FFFF}]

    80 is hex for 128, the first extended ASCII character.

    After hitting «find next» and highlighting what appears to be empty space, you can close your search dialog and press Ctrl + C to copy to clipboard.

    Then paste the character into a Unicode search tool.
    I usually use an online one.
    http://unicode.scarfboy.com/

Example:

I had a bullet point (•) in my code somehow.
The Unicode value is 2022 (hex), but when read as ASCII by the compiler
you get 342 200 242 (3 octal values). It’s not as simple as converting each octal values to hex and smashing them together. So «E2 80 A2» is not the hexadecimal Unicode point in your code.

Peter Mortensen's user avatar

answered Jan 24, 2019 at 18:01

KANJICODER's user avatar

KANJICODERKANJICODER

3,47729 silver badges16 bronze badges

5

I got the same with a character that visibly appeared as an asterisk, but it was a UTF-8 sequence instead:

Encoder * st;

When compiled, it returned:

g.c:2:1: error: stray ‘342’ in program
g.c:2:1: error: stray ‘210’ in program
g.c:2:1: error: stray ‘227’ in program

342 210 227 turns out to be UTF-8 for ASTERISK OPERATOR (Unicode code point U+2217).

Deleting the ‘*’ and typing it again fixed the problem.

Peter Mortensen's user avatar

answered Jul 21, 2016 at 9:51

TheMagicCow's user avatar

2

Whenever the compiler found a special character, it gives these kind of compile errors. The error I found is as follows:

error: stray ‘302’ in program and error: stray ‘240’ in program

….

It is some piece of code I copied from a chat messenger. In Facebook Messenger, it was a special character only. After copying into the Vim editor it changed to the correct character only. But the compiler was giving the above error .. then .. that statement I wrote manually after .. it got resolved… 🙂

Peter Mortensen's user avatar

answered Aug 20, 2015 at 5:55

visu's user avatar

visuvisu

212 bronze badges

It’s perhaps because you copied code from the Internet (from a site which has perhaps not an ASCII encoded page, but a UTF-8 encoded page), so you can convert the code to ASCII from this site:

«http://www.percederberg.net/tools/text_converter.html»

There you can either detect errors manually by converting it back to UTF-8, or you can automatically convert it to ASCII and remove all the stray characters.

Peter Mortensen's user avatar

answered Feb 3, 2016 at 11:14

Agrim Gupta's user avatar

1

This problem comes when you have copied some text from an HTML page or you have done modification in a Windows environment and are trying to compile in a Unix/Solaris environment.

Please do «dos2unix» to remove the special characters from the file:

dos2unix fileName.ext fileName.ext

Peter Mortensen's user avatar

answered Aug 5, 2015 at 13:05

Saifu Khan's user avatar

Invalid character in your code.

It is a common copy-paste error, especially when code is copied from Microsoft Word documents or PDF files.

Peter Mortensen's user avatar

answered Apr 20, 2019 at 10:25

Victor Mwenda's user avatar

I noticed an issue in using the above tr command. The tr command COMPLETELY removes the «smart quotes». It would be better to replace the «smart quotes» with something like this.

This will give you a quick preview of what will be replaced.

sed s/[”“]/'"'/g File.txt

This will do the replacements and put the replacement in a new file called WithoutSmartQuotes.txt.

sed s/[”“]/'"'/g File.txt > WithoutSmartQuotes.txt

This will overwrite the original file.

sed -i ".bk" s/[”“]/'"'/g File.txt

answered Nov 13, 2014 at 13:19

cokedude's user avatar

cokedudecokedude

3591 gold badge10 silver badges20 bronze badges

1

The explanations given here are correct. I just wanted to add that this problem might be because you copied the code from somewhere, from a website or a PDF file due to which there are some invalid characters in the code.

Try to find those invalid characters, or just retype the code if you can’t. It will definitely compile then.

Source: stray error reason

Peter Mortensen's user avatar

answered Apr 27, 2014 at 5:02

ravi's user avatar

raviravi

8402 gold badges6 silver badges13 bronze badges

With me, this error occurred when I copied and pasted code in text format to my editor (gedit).

The code was in a text document (.odt). I copied it and pasted it into gedit.

If you did the same, you have manually rewrite the code.

Peter Mortensen's user avatar

answered Jul 8, 2014 at 15:54

Lukasavicus's user avatar

1

For some weird reason, the following code doesn’t compile. I get a «stray ‘302’ in program» error around volatile unsigned int encoderPos = 0;, and I have no idea what the issue is. I’ve been trying to figure this out for over 40min, and nothing works. It doesn’t make any sense 😭

#include <U8g2lib.h>
#include <SPI.h>

//Pin definitions:

const int control_PWM = A3; //PWM output for the delay 

const int btn_1 = 1; //Button for mode 1
const int btn_2 = 4; //Button for mode 2
const int btn_3 = 5; //Button for mode 3

const int r_A = 2; //Rotary encoder A's data
const int r_B = 3; //Rotary encoder A's data
const int r_SW = 0; //Rotary encoder's button data

const int oled_CLK = 9; //SPI cloack
const int oled_MOSI = 8; //MOSI pin
const int oled_CS = 7; //Chip Select pin
const int oled_DC = 6; //OLED's D/C pin
U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

int mode = 1; //1: RGB, 2: HSL, 3: Distance control
int value_selection = 1; //Actual value selectrion
int value1 = 0; //red in mode 1; tint in mode 2
int value2 = 0; ////green in mode 1; saturation in mode 2
int value3 = 0; //blue in mode 1; luminosity in mode 2

volatile unsigned int encoderPos = 0;  // rotary encoder's current position
unsigned int lastReportedPos = 1;   // rotary encoder's previous position
static boolean rotating=false;      // is the encoder activity status

// interrupter variables
boolean A_set = false;              
boolean B_set = false;
boolean A_change = false;
boolean B_change= false;
void setup() {

}

void loop() {
}

Offline

Зарегистрирован: 29.12.2017

При попытке компилирования выдаёт эту ошибку

#include <Wire.h>                           // Подключаем библиотеку Wire
#include <LiquidCrystal.h>              // Подключаем библиотеку LiquidCrystal
#include <DallasTemperature.h>              // Подключаем библиотеку DallasTempature
#define DS18B20 2                           // Указываем, к какому выводу подключена DQ
 
byte simvol[8]   = {B11100,B10100,B11100,B00000,B00000,B00000,B00000,B00000,}; // Символ градуса
 
LiquidCrystal_I2C lcd(0x27,16,2);           // Задаем адрес и размер дисплея
OneWire oneWire(DS18B20);                   
DallasTemperature sensors(&oneWire);
 
void setup()
{
  sensors.begin();                           // Запуск библиотеки, по умолчанию 9 бит, то есть кратность 0.5 градуса 
  lcd.init();                                // Инициализация lcd    
  lcd.backlight();                           // Включаем подсветку
  lcd.setCursor(2,0);                        // Устанавливаем курсор на 1 строку, ячейка 2
  lcd.print("TEMP");                         // Выводим текст
  lcd.setCursor(2,1);                        // Устанавливаем курсор на 2 строку, ячейка 2 
  lcd.print("MADE IN CHINA");                 // Выводим текст
}
void loop()
{
  int temp = sensors.requestTemperatures();;
  lcd.createChar(1, simvol);                  // Создаем символ под номером 1
  sensors.requestTemperatures();              // Считываем показания температуры 
  lcd.setCursor(7,0);                         // Устанавливаем курсор на 1 строку, ячейка 7 
  lcd.print(sensors.getTempCByIndex(0));      // Выводим показания температуры
  lcd.setCursor(12,0);                        // Устанавливаем курсор на 1 строку, ячейка 12  
  lcd.print("1");                            // Выводим символ градуса
  lcd.setCursor(13,0);                        // Устанавливаем курсор на 1 строку, ячейка 13 
  lcd.print("C");                             // Выводим текст 
if(temp < 35)
{
  tone (9, 100);
  }
}

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

exit status 1

stray ‘302’ in program

и все. Выделяется последняя строчка. Если ее удалить, выделиться следующая. и так далее.

В чем дело?

//передатчик

#include <VirtualWire.h>

void setup()

{

vw_set_ptt_inverted(true); // Required by the RF module

vw_setup(2000); // bps connection speed

vw_set_tx_pin(3); // Arduino pin to connect the receiver data pin

}

void loop() {

//Message to send:

const char *msg = «12347779999999999999999999999567»;

vw_send((uint8_t *)msg, strlen(msg));

vw_wait_tx();

delay(200);

}

здесь таже проблема. только выделяется последняя скобка))

post-0-0-01856600-1456419352_thumb.pngpost-0-0-31979400-1456419361_thumb.png

//приемник

#include <VirtualWire.h>

void setup()

{

Serial.begin(9600); // Configure the serial connection to the computer

vw_set_ptt_inverted(true); // Required by the RF module

vw_setup(2000); // bps connection speed

vw_set_rx_pin(3); // Arduino pin to connect the receiver data pin

vw_rx_start(); // Start the receiver

}

void loop()

{

uint8_t buf[VW_MAX_MESSAGE_LEN];

uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen)) // We check if we have received data

{

int i;

// Message with proper check

for (i = 0; i < buflen; i++)

{

Serial.write(buf); // The received data is stored in the buffer

// and sent through the serial port to the computer

}

Serial.println();

}

}

stray error Arduino

stray error Arduino

One of the common errors you will see while programming your Arduino is a stray error. There are a number of causes for it. It is usual to see the following stray errors in your code,

  • error stray ‘ 342’ in program.
  • error stray ‘#’ in program.
  • or stray ‘ 315’ in program.
  • stray ‘’ in program .
  • stray ‘302’ in program.
  • error stray ‘ 240’ in program.

It is quite frustrating to deal with all these errors. Watch the video to get rid of this error or continue reading.

Why you get Stray errors?

If you are having a stray error on the compilation of code, it is most likely that you have copied the code from any website which has Unicode characters.

The characters are most likely hidden characters and therefore you see stray error in the blank spaces.

How to get rid of Stray error?

when you will have this error, the compiler will indicate the line. All you have to do is to remove the invalid characters. The invalid character may or may not be visible. If you cannot see any character just remove the space before the line.

After removing all the invalid spaces and characters, your code will compile fine.

#include <CapacitiveSensor.h>

CapacitiveSensor capSensor = CapacitiveSensor(4,2);// 1M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil

int threshold = 100;//this is an important number which is a preset capacitance reading. Check the serial monitor when touching the foil or hovering the hand over the foil. You need to determine what is the ACTUAL number the sensor is reading, then change this threshold to that number in order to make the sensor to work appropriately.

const int ledPin = 12;

//define notes’ frequency
const int c = 261;//C4
const int d = 294;//D4
const int e = 329;//E4
const int f = 349;//F4
const int g = 391;//G4
const int gS = 415;//G4#
const int a = 440;//A4
const int aS = 455;//A4#
const int b = 466;//B4
const int cH = 523;//C5
const int cSH = 554;//C5#
const int dH = 587;//D5
const int dSH = 622;//D5#
const int eH = 659;//E5
const int fH = 698;//F5
const int fSH = 740;//F5#
const int gH = 784;//G5
const int gSH = 830;//G5#
const int aH = 880;//A5

//digital pin 8 is the output pin
const int buzzerPin = 8;

//define note lengths
int Q = 500;
int H = 2Q;
int E = 0.5
Q;
int S = 0.25Q;
int ED = 0.75
Q;

void setup()

{

Serial.begin(9600);

pinMode(ledPin,OUTPUT);

//Setup pin modes
pinMode(buzzerPin, OUTPUT);

}

void loop() //create a variable type long to hold the sensor’s value.

{

delay(1+H);//additional rest between repeats

long sensorValue = capSensor.capacitiveSensor(30); //30 samples

Serial.println(sensorValue); // print sensor output

if(sensorValue > threshold)

{

digitalWrite(ledPin,HIGH);
//duration is defined as quarter note 500, delay at least 1ms for each note so you can hear it

tone(buzzerPin, a, Q);
delay(1+Q);
tone(buzzerPin, a, Q);
delay(1+Q);
tone(buzzerPin, a, Q);
delay(1+Q);
tone(buzzerPin, f, ED);
delay(1+ED);
tone(buzzerPin, cH, S);
delay(1+S);
tone(buzzerPin, a, Q);
delay(1+Q);
tone(buzzerPin, f, ED);
delay(1+ED);
tone(buzzerPin, cH, S);
delay(1+S);
tone(buzzerPin, a, H);
delay(1+H);

tone(buzzerPin, eH, Q);
delay(1+Q);
tone(buzzerPin, eH, Q);
delay(1+Q);
tone(buzzerPin, eH, Q);
delay(1+Q);
tone(buzzerPin, fH, ED);
delay(1+ED);
tone(buzzerPin, cH, S);
delay(1+S);
tone(buzzerPin, gS, Q);
delay(1+Q);
tone(buzzerPin, f, ED);
delay(1+ED);
tone(buzzerPin, cH, S);
delay(1+S);
tone(buzzerPin, a, H);
delay(1+H);

delay(1+H);//additional rest between repeats

}

else{

digitalWrite(ledPin,LOW);

}

delay(10);

}

Содержание

  1. mirsovetov.net
  2. Андрощук Александр, ИТ решения, советы, заметки…
  3. stray # in program
  4. Типичные ошибки Arduino, читать всем новичкам или сносим не предупреждая!
  5. mechanic
  6. Error stray 320 in program
  7. migrated from security.stackexchange.com Oct 5 ’13 at 13:26
  8. 13 Answers 13
  9. 2 Answers 2
  10. protected by Community ♦ Jan 7 ’18 at 7:47
  11. maccatalan

mirsovetov.net

Андрощук Александр, ИТ решения, советы, заметки…

stray # in program

При компиляции проекта в Android IDE возникла ошибка

LampCore:20: error: stray ‘302’ in program

Код, который вызывал ошибку не был какой то особенный, была объявлена простенькая структура с полями:

В моем случае ошибка возникла из за того, что я случайно в названии структуры Config написал не латинский символ C. Самое интересное что с виду все кажется в порядке, а на самом деле это не так, и возникает ошибка «stray ‘320’ in program».

Так что решение — использовать только латинские символы (это не касается комментариев).

Также могут возникать другие ошибки такого же рода, только с другим кодом

Скорее всего что следующие ошибки:

error stray 2 in program

error stray 200 in program

error stray 201 in program

error stray 213 in program

error stray 223 in program

error stray 226 in program

error stray 227 in program

error stray 240 in program

error stray 253 in program

error stray 273 in program

error stray 302 in program

error stray 320 in program

error stray 321 in program

error stray 340 in program

error stray 342 in program

error stray 357 in program

error stray 361 in program

тоже связанны с этой проблемой, если это не так, пожалуйста отпишитесь в комментариях.

Источник

Типичные ошибки Arduino, читать всем новичкам или сносим не предупреждая!

mechanic

ЧИТАЕМ, НЕ ЛЕНИМСЯ!
99% всех проблем прошивки написаны здесь!

1. Плата подключается к компьютеру по USB, на ней должны замигать светодиоды. Если этого не произошло:

  • Неисправен USB кабель
  • Неисправен USB порт компьютера
  • Неисправен USB порт Arduino
  • Попробуйте другой компьютер, чтобы исключить часть проблем из списка
  • Попробуйте другую плату (желательно новую), чтобы исключить часть проблем из списка
  • На плате Arduino сгорел входной диод по линии USB из-за короткого замыкания, устроенного пользователем при сборке схемы
  • Плата Arduino сгорела полностью из-за неправильного подключения пользователем внешнего питания или короткого замыкания

2. Компьютер издаст характерный сигнал подключения нового оборудования, а при первом подключении появится окошко “Установка нового оборудования”. Если этого не произошло:

  • См. предыдущий список неисправностей
  • Кабель должен быть data-кабелем, а не “зарядным”
  • Кабель желательно втыкать напрямую в компьютер, а не через USB-хаб
  • Не установлены драйверы Arduino (во время установки IDE или из папки с программой), вернитесь к установке.

3. В списке портов (Arduino IDE/Инструменты/Порт) появится новый порт, обычно COM3. Если этого не произошло:

  • См. предыдущий список неисправностей
  • Некорректно установлен драйвер CH341 из предыдущего урока
  • Если список портов вообще неактивен – драйвер Arduino установлен некорректно, вернитесь к установке
  • Возникла системная ошибка, обратитесь к знакомому компьютерщику

Возникает на этапе сборки и компиляции прошивки. Ошибки компиляции вызваны проблемами в коде прошивки, то есть проблема сугубо софтварная. Слева от кнопки “загрузить” есть кнопка с галочкой – проверка. Во время проверки производится компиляция прошивки и выявляются ошибки, если таковые имеются. Ардуино в этом случае может быть вообще не подключена к компьютеру.

  • В некоторых случаях ошибка возникает при наличии кириллицы (русских букв) в пути к папке со скетчем. Решение: завести для скетчей отдельную папочку в корне диска с английским названием.
  • В чёрном окошке в самом низу Arduino IDE можно прочитать полный текст ошибки и понять, куда копать
  • В скачанных с интернета готовых скетчах часто возникает ошибка с описанием название_файла.h no such file or directory. Это означает, что в скетче используется библиотека , и нужно положить её в Program Files/Arduino/libraries/. Ко всем моим проектам всегда идёт папочка с использованными библиотеками, которые нужно установить. Также библиотеки всегда можно поискать в гугле по название файла.
  • При использовании каких-то особых библиотек, методов или функций, ошибкой может стать неправильно выбранная плата в “Инструменты/плата“. Пример: прошивки с библиотекой Mouse.h или Keyboard.h компилируются только для Leonardo и Micro.
  • Если прошивку пишете вы, то любые синтаксические ошибки в коде будут подсвечены, а снизу в чёрном окошке можно прочитать более детальное описание, в чём собственно косяк. Обычно указывается строка, в которой сделана ошибка, также эта строка подсвечивается красным.
  • Иногда причиной ошибки бывает слишком старая, или слишком новая версия Arduino IDE. Читайте комментарии разработчика скетча
  • Ошибка недостаточно свободного места возникает по вполне понятным причинам. Если в проекте используется плата Nano на процессоре 328p, а вы сэкономили три рубля и купили на 168 процессоре – скупой платит дважды. Оптимизация: статическая память – память, занимаемая кодом (циклы, функции). Динамическая память занята переменными.

Частые ошибки в коде, приводящие к ошибке компиляции

  • expected ‘,’ or ‘;’ – пропущена запятая или точка запятой на предыдущей строке
  • stray ‘320’ in program – русские символы в коде
  • expected unqualified-id before numeric constant – имя переменной не может начинаться с цифры
  • … was not declared in this scope – переменная или функция используется, но не объявлена. Компилятор не может её найти
  • redefinition of … – повторное объявление функции или переменной
  • storage size of … isn’t known – массив задан без указания размера

Возникают на этапе, когда прошивка собрана, скомпилирована, в ней нет критических ошибок, и производится загрузка в плату по кабелю. Ошибка может возникать как по причине неисправностей железа, так и из-за настроек программы и драйверов.

  • USB кабель, которым подключается Arduino, должен быть Data-кабелем, а не кабелем только для зарядки. Нужным нам кабелем подключаются к компьютеру плееры и смартфоны.
  • Причиной ошибки загрузки являются не установленные/криво установленные драйвера CH340, если у вас китайская NANO.
  • Также будет ошибка avrdude: ser_open(): can’t open device, если не выбран COM порт, к которому подключена Arduino. Если кроме COM1 других портов нет – читай два пункта выше, либо попробуй другой USB порт, или вообще другой компьютер.
  • Большинство проблем при загрузке, вызванных “зависанием” ардуины или загрузчика, лечатся полным отключением ардуины от питания. Потом вставляем USB и по новой прошиваем.
  • Причиной ошибки загрузки может быть неправильно выбранная плата в “Инструменты/Плата”, а также неправильно выбранный процессор в “Инструменты/Процессор”. Также в свежих версиях IDE нужно выбирать ATmega328P (Old Bootloader) для китайских плат NANO.
  • Если у вас открыт монитор COM порта в другом окне Arduino IDE или плата общается через СОМ порт с другой программой (Ambibox, HWmonitor, SerialPortPlotter и т.д.), то вы получите ошибку загрузки, потому что порт занят. Отключитесь от порта или закройте другие окна и программы.
  • Если у вас задействованы пины RX или TX – отключите от них всё! По этим пинам Arduino общается с компьютером, в том числе для загрузки прошивки.
  • Если в описании ошибки встречается bootloader is not responding и not in sync, а все предыдущие пункты этого списка проверены – с вероятностью 95% сдох загрузчик. Второй неприятный исход – загрузчик “слетел”, и его можно прошить заново.

Помимо ошибок, по причине которых проект вообще не загрузится в плату и не будет работать, есть ещё предупреждения, которые выводятся оранжевым текстом в чёрной области лога ошибок. Предупреждения могут появиться даже тогда, когда выше лога ошибок появилась надпись “Загрузка завершена“. Это означает, что в прошивке нет несовместимых с жизнью ошибок, она скомпилировалась и загрузилась в плату. Что же тогда означают предупреждения? Чаще всего можно увидеть такие:

  • # Pragma message……. – сообщения с директивой Pragma обычно выводят библиотеки, сообщая о своей версии или каких-то настройках
  • Недостаточно памяти, программа может работать нестабильно – Чуть выше этого предупреждения обычно идёт информация о задействованной памяти. Память устройства можно добивать до 99%, ничего страшного не случится. Это флэш память и во время работы она не изменяется. А вот динамическую память желательно забивать не более 85-90%, иначе реально могут быть непонятные глюки в работе, так как память постоянно “бурлит” во время работы. НО. Это зависит от скетча и в первую очередь от количества локальных переменных. Можно написать такой код, который будет стабильно работать при 99% занятой SRAM памяти. Так что ещё раз: это всего лишь предупреждение, а не ошибка.

Завершая раздел Введение в Arduino поговорим о вопросах, которые очень часто возникают у новичков:

  • Ардуину можно прошить только один раз? Нет, несколько десятков тысяч раз, всё упирается в ресурс flash памяти. А он довольно большой.
  • Как стереть/нужно ли стирать старую прошивку при загрузке новой? Память автоматически очищается при прошивке, старая прошивка автоматически удаляется.
  • Можно ли записать две прошивки, чтобы они работали вместе? Нет, при прошивке удаляются абсолютно все старые данные. Из двух прошивок нужно сделать одну, причём так, чтобы не было конфликтов.
  • Можно ли “вытащить” прошивку с уже прошитой Ардуины?Теоретически можно, но только в виде нечитаемого машинного кода, в который преобразуется прошивка на С++ при компиляции, т.е. вам это НИКАК не поможет, если вы не имеете диплом по низкоуровневому программированию.
    • Зачем это нужно? Например есть у нас прошитый девайс, и мы хотим его “клонировать”. В этом случае да, есть вариант сделать дамп прошивки и загрузить его в другую плату на таком же микроконтроллере.
    • Если есть желание почитать код – увы, прошивка считывается в виде бинарного машинного кода, превратить который обратно в читаемый Си-подобный код обычному человеку не под силу
    • Вытащить прошивку, выражаясь более научно – сделать дамп прошивки, можно при помощи ISP программатора, об этом можно почитать здесь
    • Снять дамп прошивки можно только в том случае, если разработчик не ограничил такую возможность, например записав лок-биты, запрещающие считывание Flash памяти, или вообще отключив SPI шину. Если же разработчик – вы, и есть желание максимально защитить своё устройство от копирования – гуглите про лок-биты и отключение SPI

Источник

Error stray 320 in program

I am having problem compiling the followed exploit code:

I am using: «gcc file.c» and «gcc -O2 file.c» but both of them gets the following errors:

I tried compiling them on both Kali linux and Ubuntu 10.04 and get the same result.

migrated from security.stackexchange.com Oct 5 ’13 at 13:26

This question came from our site for information security professionals.

13 Answers 13

You have an invalid character on that line. This is what I saw:

You have invalid chars in your source. If you don’t have any valid non ascii chars in your source, maybe in a double quoted string literal, you can simply convert your file back to ascii with:

Edit: method with iconv will stop at wrong chars which makes no sense. The above command line is working with the example file. Good luck 🙂

I got the same with a character that visibly appeared as an asterisk, but was a UTF-8 sequence instead.

When compiled returned:

342 210 227 turns out to be UTF-8 for ASTERISK OPERATOR.

Deleting the ‘*’ and typing it again fixed the problem.

Whenever compiler found special character .. it gives these king of compile error . what error i found is as following

error: stray ‘302’ in program and error: stray ‘240’ in program

Some piece of code i copied from chatting messanger. In messanger it was special character only.. after copiying into vim editor it changed to correct character only. But compiler was giving above error .. then .. that stamenet i wrote mannualy after .. it got resolve.. 🙂

It’s perhaps because you copied code from net ( from a site which has perhaps not an ASCII encoded page, but UTF-8 encoded page), so you can convert the code to ASCII from this site :

There you can either detect errors manually by converting it back to UTF-8, or you can automatically convert it to ASCII and remove all the stray characters.

Codo was exactly right on Oct. 5 that &current[i] is the intended text (with the currency symbol inadvertently introduced when the source was put into HTML (see original): http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c

Codo’s change makes this exploit code compile without error. I did that and was able to use the exploit on Ubuntu 12.04 to escalate to root privilege.

The explanations given here are correct. I just wanted to add that this problem might be because you copied the code from somewhere, from a website or a pdf file due to which there are some invalid characters in the code.

Try to find those invalid characters, or just retype the code if you can’t. It will definitely compile then.

With me this error ocurred when I copied and pasted a code in text format to my editor (gedit). The code was in a text document (.odt) and I copied it and pasted it into gedit. If you did the same, you have manually rewrite the code.

I noticed an issue in using the above tr command. The tr command COMPLETELY removes the «smart quotes». It would be better to replace the «smart quotes» with something like this.

This will give you a quick preview of what will be replaced.

This will do the replacements and put the replacement in a new file called WithoutSmartQuotes.txt.

sed s/[”“]/’»’/g File.txt > WithoutSmartQuotes.txt

This will overwrite the original file.

sed -i «.bk» s/[”“]/’»’/g File.txt

This problem comes when you have copied some text from html or you have done modification in windows environment and trying to compile in Unix/Solaris environment.

Please do «dos2unix» to remove the special characters from the file:

dos2unix fileName.ext fileName.ext

Sure, convert the file to ascii and blast all unicode characters away. It will probably work. BUT.

  1. You won’t know what you fixed.
  2. It will also destroy any unicode comments. Ex: //: A²+B²=C²
  3. It could potentially damage obvious logic, the code will still be broken, but the solution less obvious. For example: A string with «Smart-Quotes» (“ & ”) or a pointer with a full-width astrix ( * ). Now “SOME_THING” looks like a #define ( SOME_THING ) and *SomeType is the wrong type ( SomeType ).

Two more sugrical approaches to fixing the problem:

    Switch fonts to see the character. (It might be invisible in your current font)

Regex search all unicode characters not part non-extended ascii. In notepad++ I can search up to FFFF, which hasn’t failed me yet.

80 is hex for 128, the first extended ascii character.

After hitting «find next» and highlighting what appears to be empty space, you can close your search dialog and press CTRL+C to copy to clipboard.

Then paste the character into a unicode search tool. I usually use an online one. http://unicode.scarfboy.com/

Example: I had a bullet point (•) in my code somehow. The unicode value is 2022 (hex), but when read as ascii by the compiler you get 342 200 242 (3 octal values). It’s not as simple as converting each octal values to hex and smashing them together. So «E2 80 A2» is NOT the hex unicode point in your code.

For some weird reason, the following code doesn’t compile. I get a «stray ‘302’ in program» error around volatile unsigned int encoderPos = 0; , and I have no idea what the issue is. I’ve been trying to figure this out for over 40min, and nothing works. It doesn’t make any sense 😭

2 Answers 2

0302 is 0xc2. Somewhere in your source you have one or more non-breaking spaces (0xa0) encoded in UTF-8 (0xc2 0xa0). Use od or a similar tool to find them, and then replace them with normal spaces. Since you have non-ASCII Latin-1 characters in your source, those characters are encoded as two bytes with the first being 0xc2 or 0xc3. Remove all non-ASCII characters before proceeding.

One cause of the /(302) error is copy and paste code from a word processor. You have ASCII codes copied that add spaces, etc to your code. Go through each identified line and remove any extra spaces at the beginning and end of any identified line. Then, (Arduino IDE) go to TOOLS, Auto Format. At least, this cleared up the problem for me.

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

maccatalan

Registered

a source that compiled very well before now does not with the following error.

Here is the code :

When I let this «as it» I get compilation errors :

stray ‘320’ in program
stray ‘240’ in program

When I replace the draw-oval-in-rect instruction by :

then it works very well.

This problem depends only on the NSBezierPath instruction. I tried it on other projects, even empty projets and . nothing to do. Always the same two ununderstable errors.

Источник

Я взял sqlconnect из примера C ++ отсюда: sql connect из c ++ . Я хочу вставить данные в таблицу MySQL из C ++. Я просто пытаюсь запустить первый пример, чтобы избавиться от него. Пожалуйста, предложите, что я должен заботиться?

#include <stdlib.h>
#include <iostream>

/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Let's have MySQL count from 10 to 1..." << endl;

try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::PreparedStatement *pstmt;

/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");

stmt = con->createStatement();
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT)");
delete stmt;

/* '?' is the supported placeholder syntax */
pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)");
for (int i = 1; i <= 10; i++) {
pstmt->setInt(1, i);
pstmt->executeUpdate();
}
delete pstmt;

/* Select in ascending order */
pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
res = pstmt->executeQuery();

/* Fetch in reverse = descending order! */
res->afterLast();
while (res->previous())
cout << "t... MySQL counts: " << res->getInt("id") << endl;
delete res;

delete pstmt;
delete con;

} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << »
" )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Все хорошо, почему это дает ошибку:

temp.cpp:65:3: error: stray ‘302’ in program
temp.cpp:65:3: error: stray ‘273’ in program
temp.cpp:69:3: error: stray ‘302’ in program
temp.cpp:69:3: error: stray ‘273’ in program

Я видел подобную нить на SO, но все же это не решается!

1

Решение

Где-то в строках 65 и 69 у вас есть нечетные символы. Они могут быть невидимыми символами, поэтому в общем случае, когда вы сталкиваетесь с этой ошибкой, просто удалите всю строку и введите ее снова.

В этом случае у вас есть несколько странных символов здесь:

cout << "(" << __FUNCTION__ << ") on line " »
^^
What's this ?

Вы, вероятно, должны удалить это, и то же самое несколько строк ниже.

3

Другие решения

Какая «похожая тема»? Был один недавно, и проблема была описана как вызванная копирования вставки код с сайта, который переводил прямые кавычки и черточки в фигурные кавычки и черточки. Они, в свою очередь, транслитерировались с использованием UTF-8 и действительно:

302 (восьмеричное) — это «В» — 0xC2
273 — это «» »- 0xBB

Это дает полный действительный код UTF8 «0xC2BB», который происходит снова быть персонажем «» ». Теперь посмотрите на строку 65 в вашем коде — так оно и есть, как сказано в сообщении об ошибке.

1

Поскольку вы уверены, что это вызвано ударами Shift + Space, вы можете проверить, что делает сам X. Первый забег xev из командной строки нажмите Shift + Space и проверьте вывод. Например, я вижу:

$ xev
KeyPress event, serial 29, synthetic NO, window 0x2000001,
    root 0x3a, subw 0x0, time 4114211795, (-576,-249), root:(414,593),
    state 0x0, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyPress event, serial 29, synthetic NO, window 0x2000001,
    root 0x3a, subw 0x0, time 4114213059, (-576,-249), root:(414,593),
    state 0x1, keycode 65 (keysym 0x20, space), same_screen YES,
    XLookupString gives 1 bytes: (20) " "
    XmbLookupString gives 1 bytes: (20) " "
    XFilterEvent returns: False
...

Затем запустите xmodmap -pk и найдите ключевой код (пробел должен быть 65, как указано выше, но проверьте вывод xev).

Если вы видите что-то вроде

     65         0x0020 (space)

Тогда X этого не делает. С другой стороны, если я выберу клавишу символа, is модифицирован shift, Я вижу что-то вроде этого:

     58         0x006d (m)      0x004d (M)

Если у вас есть два или более keyyms для вашего ключевого кода, X является виновником. В этом случае что-то вроде xmodmap -e 'keycode 65 space' должно сработать.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка store data structure corruption windows 10
  • Ошибка stopcode windows 10 что делать