Colin Null
Colin Null

Reputation: 139

Where am I going wrong when allocating memory in this simple C program?

The goal of the program is to get the user input from the terminal, and then print out the last character of each word the user inputted.

For example, "Hello World" should print out "od".

Here is the code. I am not sure where I am going wrong when I try to resize the char pointer. The code follows.

The issue only occurs when I use -fsanitize=address in the parameters for gcc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
    char *shortened = NULL;
    int i = 1;
    while(argv[i] != NULL)
    {
        shortened = realloc(shortened, 1 * (sizeof(char)));
        int length = strlen(argv[i]);
        char* curWord = argv[i];
        shortened[i-1] = curWord[length -1];
        i++;
    }
    printf("%s\n", shortened);
    return 0;
}

Upvotes: 2

Views: 69

Answers (3)

Sam Hartman
Sam Hartman

Reputation: 6489

Your call to realloc allways allocates only one character. Don't you want I characters? realloc(sizeof(char)*(1+i));

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

You want to realloc i characters, plus one for the null terminator, so change this (which allocates just one character):

shortened = realloc(shortened, 1 * (sizeof(char)));

to this:

shortened = realloc(shortened, (i + 1) * (sizeof(char)));

Upvotes: 2

Neo
Neo

Reputation: 3786

First, to answer your question - realloc gets as second argument the new size, not the increase in size. You need to use the counting of how many words did you have, and change the size accordingly.

Second, argv contains the command line arguments, meaning the tokens written after executable name. To get input from the user you might want to use scanf.

Upvotes: 0

Related Questions