G
G
gaki2022-03-16 06:07:28
C++ / C#
gaki, 2022-03-16 06:07:28

What to do if an exception breakpoint is hit during debugging?

Source
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <locale.h>

void get_str ( char *str )
{
  int i;
  char c = getchar ( );

  for ( i = 0; c != EOF && c != '\n'; i++ )
  {
    str[i] = c;
    c = getchar ( );

  }
  str[i] = '\0';
}


int main ( void )
{
  setlocale ( LC_ALL, "RUSSIAN" );
  char str = 0, *pStr = &str;

  get_str ( pStr );

  for ( int i = 0; pStr[i] != '\0'; i++ )
  {
    printf ( "\n->%c", pStr[i] );

  }

  free ( pStr );

  return 0;
}

The purpose of the program is to write a string using pointers (imitation of gets).

Comment: in visual studio 2019, when debugging, a breakpoint pops up without any information (all entered characters are output). On 2 other Online compilers, a problem like "free (): invalid pointer" pops up and the last entered character is not displayed, or they do not see the problem and process it so that my crooked code at least somehow works.
I don't want to just copy the implementation of gets, because I still can't fully understand it.

Question: Tell the stupid one, where did he make mistakes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-03-16
@wataru

char str = 0, *pStr = &str;
It's very, very wrong to do that. A string is an array of char in memory. The pointer points to the beginning of this chunk in memory. You take one variable, and then work with it as with an array.
You need to allocate memory for the string. Or a static array, or malloc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question