0

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?

6
  • 2
    Off topic: I would prefer for(char const *p = buf; *p; ++p) cout << *p << std::endl;. This way the scope of p is limited, p is pointer to const, which can prevent accident. Stepping is also on a dedicated place. BTW printBuffer should accept char const * buf, because it does not want to write into the buffer. Also in resetBuffer &buf[0] is unnecessary, you can write buf. The sizeof(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" Commented Apr 15, 2020 at 10:51
  • @Notinlist Thanks for pointing that out. I will amend my code to reflect your suggestions. Cheers! Commented Apr 15, 2020 at 10:56
  • cout << "...printing buffer:" << endl; In C, a string literal cannot be the rightside operand of a << operator. Maybe you are using C++? Commented Apr 15, 2020 at 11:03
  • @wildplasser I am using cout only 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. Commented Apr 15, 2020 at 11:05
  • 1
    Please use the correct language tags. Commented Apr 15, 2020 at 11:08

1 Answer 1

1

You are checking the address instead of the value at the address.

Replace while(p) with while(*p)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.