vtolentino
vtolentino

Reputation: 784

Segmentation Fault while printing char array through pointer in C

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?

Upvotes: 0

Views: 39

Answers (1)

Mickael B.
Mickael B.

Reputation: 5205

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

Replace while(p) with while(*p)

Upvotes: 1

Related Questions