AALC
AALC

Reputation: 93

C sprintf function crashing my program

I'm watching a course online learning C and I stumbled upon something that is crashing my program. In the video they show the following code snippet :

#include <stdio.h>

int main()
{
    char* ch;
    int num = 12345;
    sprintf(ch, "%d", num);
    printf("%s\n", ch);
    return(0);
}

I've decided to make my own little program and test it. Here's the code I've written :

#include <stdio.h>

#define A 65

int main()
{
    int n = A;
    printf("n is equal to %d\n", n);
    n = atoi("10");
    printf("n is equal to %d\n", n);
    char* ch;
    sprintf(ch, "%d", n);
    printf("ch is equal to %s\n", ch);
    return 0;
}

When I run my program, the output is as follow :

n is equal to 65
n is equal to 10

After this part my program crashes. I assume the sprintf function is causing this but I'm not sure why, I'm new to the language so I wouldn't know, I think I've done everything correctly judging by the code snippets that was shown in the video. Could someone please explain me what I did wrong ?

Thanks in advance.

Upvotes: 0

Views: 6138

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

In the video they show the following code snippet: [...]

If this is a snippet that they say should work, stop watching that video: the snippet has undefined behavior, there is no chance that it would work properly unless by an unlucky coincidence.

I've decided to make my own little program and test it.

Your program has the same exact problem: the buffer to which sprintf is writing has not been initialized. Change the declaration of ch to allocate some space to it, like this:

char ch[20];

This will prevent your code from writing to memory pointed to by an uninitialized pointer, fixing the undefined behavior.

Could you explain to me how char* could be used?

If you would like to use char*, assign it a result of malloc of a proper size, and free the result at the end:

char *ch = malloc(20);
... // Put the rest of the code here
// Add this line before the end:
free(ch);

Upvotes: 5

Mognom
Mognom

Reputation: 214

You need to alocate memory for ch or else use an array instead of a pointer.

char* ch = malloc(sizeyouwant * sizeof(char));

Where sizeyouwant is the number of characters you will store.

Upvotes: 2

thumbmunkeys
thumbmunkeys

Reputation: 20764

The problem is here:

char* ch;

this is just a char pointer, it needs to point to allocated memory to hold the string:

char ch[32];

Upvotes: 0

Related Questions