I am brushing up some on C coding for embedded programming, and I can't figure out why the following is throwing a segmentation fault error. I thought that by checking whether the pointer is pointing to NULL would suffice, but it does not seem the case.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char json[] = "Authentication:YERL90\nredLedBri:400\nredLedOn:true\n";
char inData[100];
void printBuffer(char * buf) {
cout << "...printing buffer:" << endl;
char * p = buf;
while(p) {
cout << *p << endl;
p++;
}
cout << "...end printing" << endl;
}
void resetBuffer(char * buf)
{
memset(&buf[0], 0, sizeof(buf));
}
int main()
{
printBuffer(json);
return 0;
}
Any ideas what went wrong?
for(char const *p = buf; *p; ++p) cout << *p << std::endl;. This way the scope of p is limited, p is pointer toconst, which can prevent accident. Stepping is also on a dedicated place. BTWprintBuffershould acceptchar const * buf, because it does not want to write into the buffer. Also inresetBuffer&buf[0]is unnecessary, you can writebuf. Thesizeof(buf)expression will be evaluated to the size of a pointer not as size of the array behind the pointer. You need to accept size there. Or google "Template parameter deduction from array dimensions"cout << "...printing buffer:" << endl;In C, a string literal cannot be the rightside operand of a<<operator. Maybe you are using C++?coutonly to debug the code. The code belongs originally to a MCU where I am planning to parse incoming JSON data via C. I find it easier to debug it with a remote compiler instead of uploading the file to the MCU all the time.